简体   繁体   English

Java XML 读卡器错误

[英]Java XML Reader error

I get an error when i run the beginning of my XML reader:运行 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 is giving me the following output: netbeans 给了我以下 output:

run:
XML Reader
The root of this doc is database
2 addresses in database
java.lang.NullPointerException
Address #0
Trowable error
    at xmlreader.XMLreader.main(XMLreader.java:42)

Could someone help me figure this one out?有人可以帮我解决这个问题吗?

You're not checking if there IS an element 0. Essentially, .item() will return null if the index isn't valid, as such there may not be an item with index 0 which returns null and then you try to call getChildNodes() on the null pointer.您没有检查是否存在元素 0。本质上,如果索引无效,.item() 将返回 null,因此可能没有索引为 0 的项目返回 null 然后您尝试调用 getChildNodes () 在 null 指针上。 Hence your NPE.因此,您的 NPE。

You should be iterating over the elements in the node list.您应该遍历节点列表中的元素。

change改变

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM