简体   繁体   中英

Null pointer exception on existing tag XML Java

I am using the XML file here

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. Why is this? The objects exist in the XML file as you can see in the link above.

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.

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());
    }
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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