gpt4 book ai didi

java - XML 读取错误的选项卡

转载 作者:行者123 更新时间:2023-11-30 03:08:01 25 4
gpt4 key购买 nike

我正在尝试读取一个 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>

当我运行程序时发生的情况是,对于每条道路,他都会打印所有路段,例如,对于道路“EO1”,程序会打印 3 个路段,而他应该只打印 id=01 和 id=02 的路段.

这是我的 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());

}
}
}
}

最佳答案

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

关于java - XML 读取错误的选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com