0

我想出了如何处理“正常”的 XML 树。但我从第 3 方服务器收到以下字符串:

<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"/>
4

1 回答 1

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()函数获取带有名称的属性。

于 2013-07-22T18:16:03.580 回答