Java 从 XML 中的子节点获取父信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18227252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:31:09  来源:igfitidea点击:

Getting parent information from child node in XML

javaandroidxmlparsing

提问by Roboute Guilliman

I currently have some xml along the lines of:

我目前有一些 xml:

<Schools>
    <School SchoolName="name1" ... >
        <Students> 
            <Student studentName="student1" .../>
            <Student studentName="student2" .../>
        </Stuidents>
    </School>
    <School SchoolName="name2" ...>
        <Students>
            <Student studentName="student3" ... />
            <Student studentName="student3" ... />
        </Students>
    </School>
</Schools>

If I make a node list of "School" and "Student" using a DOM parser, within the Student node list how am I able to get SchoolName from the student so that I am able to save in a Database/Student Class : StudentName, Student Details, SchoolName.

如果我使用 DOM 解析器制作“学校”和“学生”的节点列表,在学生节点列表中,我如何从学生那里获取 SchoolName 以便我能够保存在数据库/学生类中:StudentName,学生详细信息,学校名称。

NodeList schoolNodeList = docEle.getElementsByTagName("School");
NodeList studentNodeList = docEle.getElementsByTagName("Student");

parseStudentNodeList(studentNodeList);

private void parseStudentNodeList(NodeList studentsNodeList)
{
    Student student = new Student();
    for (int i = 0; i < studentNodeList.getLength(); i++)
    {
        Element el (Element) studentNodeList.item(i);
        student.setName(el.getAttribute("studentName"));
        student.setSchool( /* Help needed here */ );
    }
}

Preferably by not adding a "SchoolName" variable into the Student section.

最好不要在学生部分添加“学校名称”变量。

采纳答案by Developer Marius ?il?nas

Each node has method getParentNode(), you could get node's parent node.

每个节点都有方法getParentNode(),您可以获取节点的父节点。