从标记名称Java获取XML信息

时间:2015-06-18 11:12:15

标签: java xml

XML:

<ArrayOfObjStationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://api.irishrail.ie/realtime/">
    <objStationData>
        <Servertime>2015-06-18T12:46:40.02</Servertime>
        <Traincode>E813</Traincode>
        <Stationfullname>Dublin Pearse</Stationfullname>
        <Stationcode>PERSE</Stationcode>
        <Querytime>12:46:40</Querytime>
        <Traindate>18 Jun 2015</Traindate>
        <Origin>Greystones</Origin>
        <Destination>Malahide</Destination>
        <Origintime>12:00</Origintime>
        <Destinationtime>13:20</Destinationtime>
        <Status>En Route</Status>
        <Lastlocation>Departed Sandymount</Lastlocation>
        <Duein>7</Duein>
        <Late>4</Late>
        <Exparrival>12:52</Exparrival>
        <Expdepart>12:53</Expdepart>
        <Scharrival>12:48</Scharrival>
        <Schdepart>12:49</Schdepart>
        <Direction>Northbound</Direction>
        <Traintype>DART</Traintype>
        <Locationtype>S</Locationtype>
    </objStationData>
    <objStationData>
        ...
    </objStationData>
</ArrayOfObjStationData>

代码:

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).tagName.equals("Direction"){   // what should go here 
        doSomething();
    }
}

修改

我认为是这样的:

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

虽然这给了我一个空指针异常

3 个答案:

答案 0 :(得分:1)

像这样

public static void main(String[] args) throws MalformedURLException, SAXException, IOException{

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

// Get the DOM Builder
DocumentBuilder docBuilder;
try {
    docBuilder = factory.newDocumentBuilder();
    String dstation ="Dublin%20Pearse";

    URL url = new URL("http://api.irishrail.ie/realtime/realtime.asmx/getStationDataByNameXML?StationDesc=" + dstation);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.connect();
    Document doc = (Document) docBuilder.parse(connection.getInputStream());
    doc.getDocumentElement().normalize();
    NodeList trains = doc.getElementsByTagName("objStationData");
    NodeList nodes = trains.item(0).getChildNodes();

    for(int i = 0; i<nodes.getLength(); i++){
        if(nodes.item(i).getNodeName().equals("Direction")){   // what should go here 
            // do something
        }

    }
} catch (ParserConfigurationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

}

答案 1 :(得分:0)

如果你想从java中的xml获取信息,你可以使用Marshaller。我举一个简单的例子,你如何阅读xml中的所有信息。

http://www.mkyong.com/java/jaxb-hello-world-example/

答案 2 :(得分:0)

如果您使用的是Java 8,则可以尝试使用XmlDynamic

XmlDynamic stations = new XmlDynamic(
    "<ArrayOfObjStationData>" +
        "<objStationData>" +
            "<Direction>Northbound</Direction>" +
        "</objStationData>" +
        "<objStationData>" +
            "<Direction>Southbound</Direction>" +
        "</objStationData>" +
    "</ArrayOfObjStationData>");

stations.get("ArrayOfObjStationData").children()
    .filter(XmlDynamic.hasElementName("objStationData"))
    .forEach(stationData -> {
        // doSomething()

        // print out all Direction children text, Northbound & Southbound
        System.out.println(stationData.get("Direction").asString());
    });

请参阅https://github.com/alexheretic/dynamics#xml-dynamics