我有以下xml:
<fitness>
<group id="1" name = "firstGroup">
<exercises id="1" name = "exercise1">
<implementation> Hw
</implementation>
<videoUrl> APGw5Xi8xfQ </videoUrl>
</exercises>
</group>
<group id = "2" name = "group2">
<exercises id = "5" name = "exercise5">
<implementation>just do it</implementation>
<videoUrl>let's see it</videoUrl>
</exercises>
</group>
<group id = "3" name = "group3">
<exercises id = "6" name = "exercise6">
<implementation>just do it</implementation>
<videoUrl>let's see it</videoUrl>
</exercises>
</group>
</fitness>
我需要获取有关一组内所有练习的信息。问题是我无法获得关于一组练习的信息,我只能获得有关所有练习的信息,但我不需要它。
我的代码:
public void parseFile(InputStream file) throws Exception {
// Standart declaration for dom parser
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
doc.getDocumentElement().normalize();
NodeList group = doc.getElementsByTagName("group");
for (int temp = 0; temp < group.getLength(); temp++) {
System.out.println("----------------------------");
Node groupNode = group.item(temp);
Element groupElement = (Element) groupNode;
//Adding group name to the DB
addToMuscleGroupDb(groupElement.getAttribute("name"));
//FIXME I should take exercises which are inside current group
// But I take all exercises
String muscleGroupId = groupElement.getAttribute("id");
NodeList exercises = doc.getElementsByTagName("exercises");
for (int count = 0; count < exercises.getLength(); count++) {
Node exerciseNode = exercises.item(count);
Element eElement = (Element) exerciseNode;
//Adding exercises to DB
addToExercisesForGroupDb(muscleGroupId, eElement.getAttribute("name"));
System.out.println("Exercise :" + eElement.getAttribute("name") + ", id:");
//Adding to individual exercise DB
String implementation = eElement.getElementsByTagName("implementation").item(0).getTextContent();
String videoUrl = eElement.getElementsByTagName("videoUrl").item(0).getTextContent();
String exerciseId = eElement.getAttribute("id");
addToIndividualExerciseDb(implementation, exerciseId, videoUrl);
}
}
}
}
输出结果为:
1
Exercise :exercise1, id:1
Exercise :exercise5, id:1
Exercise :exercise6, id:1
----------------------------
2
Exercise :exercise1, id:2
Exercise :exercise5, id:2
Exercise :exercise6, id:2
----------------------------
3
Exercise :exercise1, id:3
Exercise :exercise5, id:3
Exercise :exercise6, id:3
但我需要:
1
Exercise :exercise1, id:1
----------------------------
2
Exercise :exercise5, id:2
----------------------------
3
Exercise :exercise6, id:3
答案 0 :(得分:1)
而不是NodeList exercises = doc.getElementsByTagName("exercises");
,您应该使用NodeList exercises = groupElement.getElementsByTagName("exercises");
。
这样,您只会在<exercices>
内检索<group>
。