我正在尝试将这个特定的纬度和经度字符串解析到我用 Java 编写的 XML Parser 中,但我不确定要使用什么元素,因为 point 没有结束/>
<data>
<location>
<location-key>point1</location-key>
<point latitude="39.95" longitude="-75.17"/>
</location>
<moreWeatherInformation applicable-location="point1">
http://forecast.weather.gov/MapClick.php?textField1=39.95&textField2=-75.17
</moreWeatherInformation>
<time-layout time-coordinate="local" summarization="none">
<layout-key>k-p24h-n1-1</layout-key>
<start-valid-time>2013-10-30T08:00:00-04:00</start-valid-time>
<end-valid-time>2013-10-30T20:00:00-04:00</end-valid-time>
</time-layout>
<time-layout time-coordinate="local" summarization="none">
<layout-key>k-p24h-n2-2</layout-key>
<start-valid-time>2013-10-29T20:00:00-04:00</start-valid-time>
<end-valid-time>2013-10-30T09:00:00-04:00</end-valid-time>
<start-valid-time>2013-10-30T20:00:00-04:00</start-valid-time>
<end-valid-time>2013-10-31T09:00:00-04:00</end-valid-time>
</time-layout>
<parameters applicable-location="point1">
<temperature type="maximum" units="Fahrenheit" time-layout="k-p24h-n1-1">
<name>Daily Maximum Temperature</name>
<value>64</value>
</temperature>
<temperature type="minimum" units="Fahrenheit" time-layout="k-p24h-n2-2">
<name>Daily Minimum Temperature</name>
<value>44</value>
<value>52</value>
</temperature>
</parameters>
</data>
使用下面的代码,我得到以下输出。
try {
File newXMLFile = new File("H:\\520\\SOAP Data Acquisition\\testNOAA.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(newXMLFile);
doc.getDocumentElement().normalize();
System.out.println("Title: " + doc.getElementsByTagName("title").item(0).getTextContent());
System.out.println("Field: " + doc.getElementsByTagName("field").item(0).getTextContent());
System.out.println("category: " + doc.getElementsByTagName("category").item(0).getTextContent());
System.out.println("Date Created: " + doc.getElementsByTagName("creation-date").item(0).getTextContent());
NodeList nList = doc.getElementsByTagName("data");
for(int i = 0; i < nList.getLength(); i++){
Node nNode = nList.item(i);
System.out.println("\nCurrent Element: " + nNode.getNodeName());
if(nNode.getNodeType() == Node.ELEMENT_NODE){
Element eElement = (Element) nNode;
System.out.println("Location: " + eElement.getAttribute("point"));
System.out.println("Start Time: "+eElement.getElementsByTagName("start-valid-time").item(0).getTextContent());
System.out.println("End Time: "+eElement.getElementsByTagName("end-valid-time").item(0).getTextContent());
System.out.println("");
}
}
}catch(Exception e){
e.printStackTrace();
}
输出:
Title: NOAA's National Weather Service Forecast Data
Field: meteorological
category: forecast
Date Created: 2013-10-29T14:42:58Z
Current Element: data
Location:
Start Time: 2013-10-30T08:00:00-04:00
End Time: 2013-10-30T20:00:00-04:00