这是我需要解析的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);
}
答案 0 :(得分:2)
您可以使用getElementsByTagName获取元素:
NodeList nodel = root.getElementsByTagName("weatherDesc");
if(nodel.getLength() > 0) {
Node item = nodel.item(0);
String weather = item.getTextContent();
}
答案 1 :(得分:1)
最好将jaxb用于xml和java对象之间的任何转换
答案 2 :(得分:0)
这将打印文档中所有weatherDesc
标记的值:
NodeList nodeList = doc.getElementsByTagName("weatherDesc");
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println("Weather: " + nodeList.item(i).getNodeValue());