一切都好。从互联网获取xml,解析为Document但是当我试图从node()获取某些值时,某些节点之间有一些值(非常混浊。)
private void parseWeather(Document srcDoc) throws Exception {
for (int a = 0; a < srcDoc.getElementsByTagName("record").getLength(); a++){
Node recordNode = srcDoc.getElementsByTagName("record").item(a);
Node temperatureNode = srcDoc.getElementsByTagName("temperature").item(a);
Node windNode = srcDoc.getElementsByTagName("wind").item(a);
Node bioNode = srcDoc.getElementsByTagName("bio").item(a);
RECORD = recordNode.getAttributes().getNamedItem("date").getNodeValue().toString();
TEMPERATURE = temperatureNode.getAttributes().getNamedItem("min").getNodeValue().toString();
WIND = windNode.getAttributes().getNamedItem("speed").getNodeValue().toString();
BIO = bioNode.getAttributes().getNamedItem("value").getNodeValue().toString();
Element element= (Element) srcDoc.getElementsByTagName("record").item(a);
NodeList status = element.getElementsByTagName("status");
NodeList text = element.getElementsByTagName("text");
Node statusNode = status.item(0);
Node textNode = text.item(0);
String statusText = statusNode.getFirstChild().getNodeValue();
String textText = textNode.getFirstChild().getNodeValue();
Log.e("Values", "STatus is " + statusText + " and text is " + textText);
}
}
这是xml文件
<root>
<forecast>
<record date="24-10-2012">
<temperature max="17" min="3" unit="°C" />
<wind speed="2 až 5" direction="SV" unit="m/s" />
<bio value="2" />
<status symbol="3">Fair</status>
<text>Very fair today.</text>
<warnings />
</record>
<record date="25-10-2012">
<temperature max="16" min="2" unit="°C" />
<wind speed="2 až 5" direction="Juhozápadný" unit="m/s" />
<bio value="3" />
<status symbol="3">Cloudy</status>
<text>Very cloudy tommorow. </text>
<warnings />
</record>
<record date="25-10-2012">
<temperature max="16" min="2" unit="°C" />
<wind speed="2 až 5" direction="Juhozápadný" unit="m/s" />
<bio value="3" />
<status symbol="3">Cloudy</status>
<text>Very cloudy tommorow. </text>
<warnings />
</record>
我得到记录,温度,风的输出生物,但不是状态和文本。而这个循环只会做一些。 有人能帮助我吗?
答案 0 :(得分:0)
状态和文本没有任何子节点,因为它们不是节点列表,它们只是节点。尝试将它们作为节点并使用status.getNodeValue()
代替。
答案 1 :(得分:0)
我找到了解决方案http://androidcodesnips.blogspot.sk/2011/05/dom-parsing-example.html
它看起来不那么容易