简体   繁体   English

现有标签XML Java上的空指针异常

[英]Null pointer exception on existing tag XML Java

I am using the XML file here 我在这里使用XML文件

I have the following code: 我有以下代码:

        Document doc = (Document) docBuilder.parse(new URL("http://api.irishrail.ie/realtime/realtime.asmx/getStationDataByNameXML?StationDesc=" + dstation).openStream());

        doc.getDocumentElement().normalize();

        NodeList trains = doc.getElementsByTagName("objStationData");

        for(int i = 0; i<trains.getLength(); i++){

                if(trains.item(i).getAttributes().getNamedItem("Direction").getTextContent().trim().equals("Northbound")){

                    System.out.println(trains.item(i).getAttributes().getNamedItem("Destination").getTextContent().trim());
                }
            }   

I get a Null Pointer exception on the if statement. 我在if语句上得到一个Null Pointer异常。 Why is this? 为什么是这样? The objects exist in the XML file as you can see in the link above. 如上链接所示,这些对象存在于XML文件中。

Something like this should work. 这样的事情应该起作用。 Since you know the structure of the XML and you are calling getElementsByTagName you know that you can safely cast the nodes from NodeList to Element objects. 由于您知道XML的结构并且正在调用getElementsByTagName ,因此知道可以安全地将节点从NodeListElement对象。

Document doc = (Document) docBuilder.parse(new URL("http://api.irishrail.ie/realtime/realtime.asmx/getStationDataByNameXML?StationDesc=" + dstation).openStream());
doc.getDocumentElement().normalize();
NodeList trains = doc.getElementsByTagName("objStationData");
for(int i = 0; i<trains.getLength(); i++){
    Element objStationDataElement = (Element)trains.item(i);
    Element directionElement = objStationDataElement.getElementsByTagName("Direction").item(0);
    if(directionElement.getTextContent().trim().equals("Northbound")){
        Element destinationElement = (Element)objStationDataElement.getElementsByTagName("Destination").item(0);
        System.out.println(destinationElement.getTextContent().trim());
    }
}   

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

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