gpt4 book ai didi

Java XML 读取器错误

转载 作者:行者123 更新时间:2023-12-02 08:14:52 28 4
gpt4 key购买 nike

当我运行 XML 阅读器的开头时出现错误:

public static void main(String[] args) 
{
System.out.println("XML Reader");

try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("database.xml");

//normalize text
doc.getDocumentElement().normalize();
System.out.println("The root of this doc is "+doc.getDocumentElement().getNodeName());

NodeList listOfAddresses = doc.getElementsByTagName("address");
int totalAddresses = listOfAddresses.getLength();
System.out.println(totalAddresses+" addresses in "+ doc.getDocumentElement().getNodeName());

//main loop
for(int i = 0; i<listOfAddresses.getLength(); i++)
{
Node items = listOfAddresses.item(i);

if(items.getNodeType() == Node.ELEMENT_NODE)
{
System.out.println("Address #"+i);

Element element = (Element)items;

NodeList nameList = element.getElementsByTagName("name");
Element nameElement = (Element)nameList.item(0);
NodeList nameOutput = nameElement.getChildNodes();


System.out.println("name: "+nameElement);
}
}


}

catch(SAXParseException err)
{
System.out.println("Sax Parse Exception error on line "+err.getLineNumber());
}

catch(SAXException e)
{
System.out.println("SAX Exception error");
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();
}

catch(Throwable t)
{
System.out.println("Trowable error");
t.printStackTrace();
}
}

netbeans 给我以下输出:

run:XML ReaderThe root of this doc is database2 addresses in databasejava.lang.NullPointerExceptionAddress #0Trowable error    at xmlreader.XMLreader.main(XMLreader.java:42)

有人可以帮我解决这个问题吗?

最佳答案

您没有检查是否存在元素 0。本质上,如果索引无效,.item() 将返回 null,因此可能不存在索引为 0 的项目返回 null,然后您尝试对空指针调用 getChildNodes()。这就是你的 NPE。

您应该迭代节点列表中的元素。

改变

Element nameElement = (Element)nameList.item(0);

for(int x = 0; x < nameList.getLength(); x++) {
nameElement = nameList.item(x);
NodeList nameOutput = nameElement.getChildNodes();
System.out.println("name: "+nameElement);
}

关于Java XML 读取器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6635368/

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