用java处理循环中的子节点

1cosmwyk  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(374)

有人能帮我用java代码来处理这个xml并得到最后提到的输出吗。提前谢谢。
xml文件:

<?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>

预期产量:
stateid name cityid name schoolid schoolname班级教师姓名numberofstudents
1泰兰加纳1海得拉巴1维达亚莱1 100
泰兰加纳1号海得拉巴1号维达亚莱1号2 xyz 101
1泰兰加纳1海得拉巴2维达亚莱2 1 100
1泰兰加纳1海得拉巴2维达亚莱2 xyz 101
2卡纳塔克邦1 banglore 1 bglr\ U vidayalay\ U 1 1 100
卡纳塔克邦1号班格罗1号bglr\ U vidayalay\ U 1号2 xyz 100

wrrgggsh

wrrgggsh1#

下载XPath3.1库(如saxon),然后执行xpath表达式

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')

其他人可能有耐心向您展示使用dom的解决方案,但我更喜欢简单的方法。

相关问题