XML processing child nodes in loop using Java

37 views Asked by At

Could someone help me with Java code to get this XML processed and get the output mentioned at the end. Thanks in advance.

XML File:

<?xml version = "1.0"?>
<Oraganization Id="123" >
    <state_name ID="1" name="Telangana">
        <city_name ID="1" name="Hyderabad">
            <school_name ID="1" school_name="Vidayalay_1">
                <record>
                    <class>1</class>
                    <TeacheName>ABC</TeacheName>
                    <NumberOfStudents>100</NumberOfStudents>
                </record>
                <record>
                    <class>2</class>
                    <TeacheName>XYZ</TeacheName>
                    <NumberOfStudents>101</NumberOfStudents>
                </record>
            </school_name>
            <school_name ID="2" school_name="Vidayalay_2">
                <record>
                    <class>1</class>
                    <TeacheName>ABC</TeacheName>
                    <NumberOfStudents>100</NumberOfStudents>
                </record>
                <record>
                    <class>2</class>
                    <TeacheName>XYZ</TeacheName>
                    <NumberOfStudents>101</NumberOfStudents>
                </record>
            </school_name>
        </city_name>
    </state_name>
    <state_name ID="2" name="Karnataka">
        <city_name ID="1" name="Banglore">
            <school_name ID="1" school_name="Bglr_Vidayalay_1">
                <record>
                    <class>1</class>
                    <TeacheName>ABC</TeacheName>
                    <NumberOfStudents>100</NumberOfStudents>
                </record>
                <record>
                    <class>2</class>
                    <TeacheName>XYZ</TeacheName>
                    <NumberOfStudents>101</NumberOfStudents>
                </record>
            </school_name>
        </city_name>
    </state_name>
</Oraganization>

Expected Output:

StateId Name CityId Name SchoolID SchoolName class TeacherName NumberOfStudents

1 Telangana 1 Hyderabad 1 Vidayalay_1 1 ABC 100

1 Telangana 1 Hyderabad 1 Vidayalay_1 2 XYZ 101

1 Telangana 1 Hyderabad 2 Vidayalay_2 1 ABC 100

1 Telangana 1 Hyderabad 2 Vidayalay_2 2 XYZ 101

2 Karnataka 1 Banglore 1 Bglr_Vidayalay_1 1 ABC 100

2 Karnataka 1 Banglore 1 Bglr_Vidayalay_1 2 XYZ 100

1

There are 1 answers

0
Michael Kay On

Download an XPath 3.1 library (such as Saxon) and then execute the XPath expression

string-join(//record ! 
    string-join(( ancestor::state_name ! (@ID, @name),
                  ancestor::city_name ! (@ID, @name),
                  ancestor::school_name ! (@ID, @school_name),
                  class, TeacheName, NumberOfStudents), ' '), '\n')

Someone else might have the patience to show you a solution using DOM, but I prefer the easy way.