我试图读取xml,我需要从每条道路获取相应的段,并将信息放在其他类中。
这是XML文件:
<section_list>
<road_section begin="n0" end="n1">
<road>"E01"</road>
<wind_speed>3 m/s</wind_speed>
<segment_list>
<segment id="01">
<height>100</height>
<number_vehicles>20</number_vehicles>
</segment>
<segment id="02">
<height>148</height>
<number_vehicles>20</number_vehicles>
</segment>
</segment_list>
</road_section>
<road_section begin="n0" end="n2">
<road>"E01"</road>
<wind_speed>3 m/s</wind_speed>
<segment_list>
<segment id="03">
<height>100</height>
<number_vehicles>100</number_vehicles>
</segment>
</segment_list>
</road_section>
</section_list>
当我运行程序时会发生的事情是,对于每条道路,他打印所有段,例如道路&#39; EO1&#39;当程序只打印段id = 01和id = 02时,程序会打印3段。
这是我的Java代码:
NodeList listSection = doc.getElementsByTagName("road_section");
for (int temp = 0; temp < listSection.getLength(); temp++) {
Node nNode = listSection.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Begin : " + eElement.getAttribute("begin") + "\tEnd: " + eElement.getAttribute("end"));
System.out.println("road : " + eElement.getElementsByTagName("road").item(0).getTextContent().replaceAll("\"", ""));
System.out.println("wind_speed : " + eElement.getElementsByTagName("wind_speed").item(0).getTextContent().trim().replaceAll("m/s", ""));
}
for (int i = 0; i < 1; i++) {
Element eElement = (Element) nNode;
NodeList listaSegmentos = eElement.getElementsByTagName("segment_list").item(i).getChildNodes();
for (int j = 0; j < listaSegmentos.getLength(); j++) {
Node nodeseg = listaSegmentos.item(cont);
if (nodeseg.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) nodeseg;
System.out.println("\nSegment id : " + el.getAttribute("id"));
System.out.println("height : " + el.getElementsByTagName("height").item(0).getTextContent().replaceAll("\"", ""));
System.out.println("number_vehicles : " + el.getElementsByTagName("number_vehicles").item(0).getTextContent().trim());
}
}
}
}
答案 0 :(得分:2)
getElementsByTagName("segment_list")
调用将获取所有segment_list
元素(对于当前road_section
),您必须将第二个内部循环限制为一次迭代而不是j < listaSegmentos.getLength()
或者根本不使用循环并执行以下操作:
if(listaSegmentos.getLength()>=1) {
Node nodeseg = listaSegmentos.item(0);
if (nodeseg.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) nodeseg;
System.out.println("\nSegment id : " + el.getAttribute("id"));
System.out.println("height : " + el.getElementsByTagName("height").item(0).getTextContent().replaceAll("\"", ""));
System.out.println("number_vehicles : " + el.getElementsByTagName("number_vehicles").item(0).getTextContent().trim());
}
}
同样适用于第一个内部循环,其条件设置为i < 1