我想出了如何处理'普通'的XML树。但是我从第三方服务器收到以下字符串:
<CallOverview>
<Calls Count="2">
<Call CallType="GeoCall" Customer="this account" StartTime="2013-07-22 17:53:22 (UTC)" Destination="+123456789" Duration="00:00:14" Charge="0.00374" CallId="1472453365"/>
<Call CallType="GeoCall" Customer="this account" StartTime="2013-07-22 16:42:45 (UTC)" Destination="+123456789" Duration="00:00:05" Charge="0.00284" CallId="1472377565"/>
</Calls>
<MoreData>False</MoreData>
</CallOverview>
我正在使用此方法检索DOM元素:
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
用这种方法得到结果:
Element e = (Element) nl.item(i); //nl is a nodelist of parent nodes
public HashMap<String, String> getResults(Element item) {
HashMap<String, String> map = new HashMap<String, String>();
NodeList results = item.getElementsByTagName(KEY_RESULT);
//I run through the node list:
map.put("RESPONSE", this.getElementValue(results.item(i)));
...
return map;
}
但是当我为这个XML尝试相同的时候,我没有得到理想的结果。 我想要一个包含目的地,持续时间和费用的电话列表。所以基本上我想要“”之间的数据:
<Call CallType="GeoCall" Customer="this account" StartTime="2013-07-22 17:53:22 (UTC)" Destination="+123456789" Duration="00:00:14" Charge="0.00374" CallId="1472453365"/>
答案 0 :(得分:1)
NodeList results = doc.getElementsByTagName("Call");
for (int i = 0; i < results.getLength(); i++) {
Element element = (Element) results.item(i);
String attribute= element.getAttribute("CallType");
String attribute2= element.getAttribute("Customer");
}
您可以使用element.getAttribute()
函数获取名称属性。