请帮我解析这个xml标签,我想用类别ID解析这个xml标签 如下......?
期望的输出:
apple 100 iphone 5 500$
apple 200 iphone 4s 300$
Samsung 300 Galaxy 4 400$
XML示例在这里:
<Items>
<category ID="99">
<MobileDetails>
<MobileName>apple</MobileName>
<MobileID>100</MobileID>
<MobileModel>iphone 5</MobileModel>
<MobileCost>500$</MobileCost>
</MobileDetails>
<MobileDetails>
<MobileName>apple</MobileName>
<MobileID>200</MobileID>
<MobileModel>iphone 4s</MobileModel>
<MobileCost>300$</MobileCost>
</MobileDetails>
</category >
<category ID="100">
<MobileDetails>
<MobileName>Samsung</MobileName>
<MobileID>300</MobileID>
<MobileModel>Galaxy 4</MobileModel>
<MobileCost>400$</MobileCost>
</MobileDetails>
</category >
</Items>
答案 0 :(得分:1)
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
Element root =(Element) doc.getDocumentElement();
//category
NodeList categoryNList = root.getElementsByTagName("category");
int categoryLength = categoryNList.getLength();
for (int i = 0; i < categoryLength; i++) {
Element element = (Element)categoryNList.item(i);
//fetch ID
String categoryID = element.getAttribute("ID");
NodeList mobileDetailsNList = element.getElementsByTagName("MobileDetails");
//inner
int MobileDetailsLength = elemnt.getElementsByTagName("MobileName");
for(int j==0;int < j <MobileDetailsLength ; j++) {
NodeList MobileDetailsNList = element.getElementsByTagName("MobileDetails");
Element element = (Element)categoryNList.item(i);
String name = mobileDetailsNList.item(0).getFirstChild().getNodeValue() ;
//... ... ...
//... ... ...
}
}
} catch (Exception e) {
}
}
maybe it will help you.