我对XML和Android开发有点新...我遇到过这个问题,我需要解析一个XML,其中的元素是相同的,并包含整个元素。这有点难以解释,请参阅下面的代码:
<tns:camera>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Eastbound</tns:direction>
</tns:congestionLocations>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Westbound</tns:direction>
</tns:congestionLocations>
<tns:description>Bond St looking east</tns:description>
<tns:direction>Eastbound</tns:direction>
<tns:group>SH16-North-Western</tns:group>
<tns:lat>-36.869</tns:lat>
<tns:lon>174.746</tns:lon>
<tns:name>SH16 1 Bond St</tns:name>
<tns:viewUrl>http://www.trafficnz.info/camera/view/130</tns:viewUrl>
</tns:camera>
基本上,我需要解析整个元素(tns:camera)并包含拥塞位置(显然彼此分开),但是在同一个类中,我将在列表视图中使用所有这些... < / p>
我将如何实现这一目标?
目前,我正在使用Pull Parser,并将其解析为类对象
PullParser代码:
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase(KEY_SITE)) {current Site
CameraSites.add(curCameraClass);
} else if (tagname.equalsIgnoreCase(KEY_DESCRIPTION)) {
curCameraClass.setDescription(curText);
}else if (tagname.equalsIgnoreCase(KEY_NAME)) {
curCameraClass.setName(curText);
}
break;
亲切的问候!
答案 0 :(得分:0)
答案 1 :(得分:0)
试试这个..
NodeList nodeList = doc.getElementsByTagName("tns:camera");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("tns:group");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
System.out.println("tns:group : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("tns:viewUrl");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
System.out.println("tns:viewUrl : "+ ((Node) nameList1.item(0)).getNodeValue());
//same as use to all tns:description,tns:direction and tns:lat etc.,
if(node.getNodeType() == Node.ELEMENT_NODE)
{
Element e = (Element) node;
NodeList resultNodeList = e.getElementsByTagName("tns:congestionLocations");
int resultNodeListSize = resultNodeList.getLength();
for(int j = 0 ; j < resultNodeListSize ; j++ )
{
Node resultNode = resultNodeList.item(j);
if(resultNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstElmnt2 = (Element) resultNode;
NodeList nameList2 = fstElmnt2.getElementsByTagName("tns:congestion");
Element nameElement2 = (Element) nameList2.item(0);
nameList2 = nameElement2.getChildNodes();
Log.v("tns:congestion", ""+((Node) nameList2.item(0)).getNodeValue());
Element fstElmnt3 = (Element) resultNode;
NodeList nameList3 = fstElmnt3.getElementsByTagName("tns:direction");
Element nameElement3 = (Element) nameList3.item(0);
nameList3 = nameElement3.getChildNodes();
Log.v("tns:direction--", ""+((Node) nameList3.item(0)).getNodeValue());
}
}
}
}