我需要一些关于如何使用Java解析XML的建议,其中有多个节点具有相同的标记。例如,如果我有一个如下所示的XML文件:
<?xml version="1.0"?>
<TrackResponse>
<TrackInfo ID="EJ958083578US">
<TrackSummary>Your item was delivered at 8:10 am on June 1 in Wilmington DE 19801.</TrackSummary>
<TrackDetail>May 30 11:07 am NOTICE LEFT WILMINGTON DE 19801.</TrackDetail>
<TrackDetail>May 30 10:08 am ARRIVAL AT UNIT WILMINGTON DE 19850.</TrackDetail>
<TrackDetail>May 29 9:55 am ACCEPT OR PICKUP EDGEWATER NJ 07020.</TrackDetail>
</TrackInfo>
</TrackResponse>
我能够获得“TrackSummary”,但我不知道如何处理“TrackDetail”,因为有超过1.该示例XML上可能有超过3个,所以我需要一种方法来处理这一点。
到目前为止,我有这段代码:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xmlResponse));
Document dom = builder.parse(is);
//Get the ROOT: "TrackResponse"
Element docEle = dom.getDocumentElement();
//Get the CHILD: "TrackInfo"
NodeList nl = docEle.getElementsByTagName("TrackInfo");
String summary = "";
//Make sure we found the child node okay
if (nl != null && nl.getLength() > 0)
{
//In the event that there is more then one node, loop
for (int i = 0 ; i < nl.getLength(); i++)
{
summary = getTextValue(docEle,"TrackSummary");
Log.d("SUMMARY", summary);
}
return summary;
}
我如何处理整个'多个TrackDetail节点'的考验?我是XML解析的新手,所以我对如何处理这样的事情有点不熟悉。
答案 0 :(得分:1)
您可以尝试这样:
public Map getValue(Element element, String str) {
NodeList n = element.getElementsByTagName(str);
for (int i = 0; i < n.getLength(); i++) {
System.out.println(getElementValue(n.item(i)));
}
return list/MapHere;
}
答案 1 :(得分:0)
如果您可以自由更改实施,那么我建议您使用here给出的实现。
你可以在字符串数组中收集trackdetail,当你在XmlPullParser.END_TAG时检查trackinfo标签结束然后停止
答案 2 :(得分:0)
您可以参考以下代码。
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
Element root = doc.getDocumentElement();
NodeList nodeList = doc.getElementsByTagName("TrackInfo");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i); // this is node under track info
// do your stuff
}
有关详情,请访问以下链接。
How to parse same name tag in xml using dom parser java?
这可能会有所帮助。