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

时间:2013-08-14 08:56:30

标签: java android xml parsing

我目前有一些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>

如果我使用DOM解析器创建“School”和“Student”的节点列表,则在Student节点列表中如何从学生中获取SchoolName,以便我能够保存在Database / Student Class中:学生姓名,学生详细信息,学校名称。

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 */ );
    }
}

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

1 个答案:

答案 0 :(得分:1)

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