gpt4 book ai didi

java - 解析java xml文件中的字符串

转载 作者:行者123 更新时间:2023-12-02 00:14:02 24 4
gpt4 key购买 nike

这是我需要解析的 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>

当前代码:我希望它打印出天气描述......在本例中为“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);
}

最佳答案

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

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

if(nodel.getLength() > 0) {
Node item = nodel.item(0);
String weather = item.getTextContent();
}

关于java - 解析java xml文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12223666/

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