0

这是我需要解析的xml文件。我想从 weatherDesc 标签中提取数据

<weather>
  <date>2012-08-31</date>
  <tempMaxC>33</tempMaxC>
  <tempMaxF>91</tempMaxF>
  <tempMinC>22</tempMinC>
  <tempMinF>71</tempMinF>
  <windspeedMiles>15</windspeedMiles>
  <windspeedKmph>24</windspeedKmph>
  <winddirection>W</winddirection>
  <winddir16Point>W</winddir16Point>
  <winddirDegree>260</winddirDegree>
  <weatherCode>113</weatherCode>
  <weatherIconUrl>
    <![CDATA[
    http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png
    ]]>
  </weatherIconUrl>
  <weatherDesc>
    <![CDATA[ Sunny ]]>
  </weatherDesc>
  <precipMM>0.0</precipMM>
</weather>  

当前代码:我希望它打印出weatherDesc ....在这种情况下为“Sunny”

URL url = new URL("http://free.worldweatheronline.com/feed/weather.ashx?   key=14d7241962022903123108&q=Pittsburgh,pa.xml");
URLConnection conn = url.openConnection();

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());  

Element root = doc.getDocumentElement();
NodeList nodel = root.getChildNodes();


for (int a = 0; a < nodel.getLength(); a++) {
     String weather = /////////////////????? code i dont know
     System.out.println(weather);
}
4

3 回答 3

2

您可以使用 getElementsByTagName 来获取元素:

NodeList nodel = root.getElementsByTagName("weatherDesc");

if(nodel.getLength() > 0) {
    Node item = nodel.item(0);
    String weather = item.getTextContent();
}
于 2012-08-31T23:56:46.090 回答
1

更好地使用 jaxb 进行 xml 和 java 对象之间的任何转换

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

于 2013-10-14T18:56:51.563 回答
0

这将打印weatherDesc文档中所有标签的值:

NodeList nodeList = doc.getElementsByTagName("weatherDesc");

for (int i = 0; i < nodeList.getLength(); i++) {
    System.out.println("Weather: " + nodeList.item(i).getNodeValue());
于 2012-08-31T23:56:58.753 回答