gpt4 book ai didi

java - 使用java读取xml文件来访问每个元素

转载 作者:行者123 更新时间:2023-12-02 11:35:01 26 4
gpt4 key购买 nike

我有一个 XML 文件,如下所示。我已经创建了一个简单的程序来读取该文件并在控制台上打印。我面临的问题是它给了我

java.lang.NullPointerException
at xmlreader.main(xmlreader.java:46)

而且它也没有读取某些值。

 <problemType>
<fleetSize>FINITE</fleetSize>
</problemType>
<vehicles>
<vehicle>
<id>1_1</id>
<typeId>type_1</typeId>
<startLocation>
<id>[x=-20.2675][y=57.4797]</id>
<coord x="-20.2675" y="57.4797"/>
</startLocation>
<endLocation>
<id>[x=-20.2675][y=57.4797]</id>
<coord x="-20.2675" y="57.4797"/>
</endLocation>
<timeSchedule>
<start>0.0</start>
<end>1.7976931348623157E308</end>
</timeSchedule>
<returnToDepot>true</returnToDepot>
</vehicle>
<vehicle>
</vehicles>

我创建了一段java代码来读取这个文件

    import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class xmlreader {

public static void main(String argv[]) {

try {

File fXmlFile = new File("C:/Users/HP/Desktop/solution.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("vehicles");

System.out.println("----------------------------");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

System.out.println("\nCurrent Element :" + nNode.getNodeName());

if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

System.out.println("id : " + eElement.getAttribute("id"));
System.out.println("typeId : " + eElement.getElementsByTagName("typeId").item(0).getTextContent());
System.out.println("startLocation : " + eElement.getElementsByTagName("startLocation").item(0).getTextContent());
System.out.println("endLocation : " + eElement.getElementsByTagName("endLocation").item(0).getTextContent());
System.out.println("timeSchedule : " + eElement.getElementsByTagName("timeSchedule").item(0).getTextContent());
System.out.println("returnTodepot : " + eElement.getElementsByTagName("returnTodepot").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}}

当我尝试运行该程序时,它给了我错误“java.lang.NullPointerException”,而且它似乎没有获取 startLocation 标记内的值。请帮助我现在有点困惑

最佳答案

由于拼写错误,您得到了空指针。

你想要一个元素:returnTodepot
而元素名称是:returnToDepot

关于java - 使用java读取xml文件来访问每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49006042/

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