gpt4 book ai didi

java - 从标签名称 Java 获取 XML 信息

转载 作者:行者123 更新时间:2023-12-01 11:24:48 27 4
gpt4 key购买 nike

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")){

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

最佳答案

类似这样

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

}

关于java - 从标签名称 Java 获取 XML 信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30913770/

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