我有這樣從XML獲取特定的節點值並添加到ArrayList中
<reg>
<user>
<Name> abc</Name>
<Email> [email protected]</Email>
<picture> sdCard/imges.145.jpg </Picture>
<Date> 12/12/2012</Date>
</user>
<user>
<Name> abc dfg</Name>
<Email> [email protected]</Email>
<picture> sdCard/imges.145.jpg </Picture>
<Date> 23/12/2013</Date>
</user>
</reg>
我想獲得特定節點的值,並將它們添加到ArrayList中顯示的XML中的ListView 我已經試過這個代碼但它只給出最後一個記錄的值
Users setUser = new Users();
final ArrayList<Users> uData = new ArrayList<Users>();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/reg/user/Name";
System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getTextContent());
setUser.setName(nodeList.item(i).getTextContent());
}
String expression1 = "/reg/user/Email";
System.out.println(expression1);
NodeList nodeList1 = (NodeList) xPath.compile(expression1).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList1.getLength(); i++) {
System.out.println(nodeList1.item(i).getTextContent());
setUser.setEmail(nodeList1.item(i).getTextContent());
}
String expression2 = "/reg/user/Picture";
System.out.println(expression2);
NodeList nodeList2 = (NodeList) xPath.compile(expression2).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList2.getLength(); i++) {
System.out.println(nodeList2.item(i).getTextContent());
setUser.setimage(nodeList2.item(i).getTextContent());
}
String expression3 = "/reg/user/LastEdited";
System.out.println(expression3);
NodeList nodeList3 = (NodeList) xPath.compile(expression3).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList3.getLength(); i++) {
System.out.println(nodeList3.item(i).getTextContent());
setUser.setDate(nodeList3.item(i).getTextContent());
} uData.add(setUser);
我該如何顯示所有記錄?
您是如何識別特定的節點? – playmaker420
在我的代碼中,我正在通過XPATH表達式來識別節點。 。 。 –
您的setUser對象將替換for循環迭代的時間。並在forloop結束時將setUser添加到uData。所以只有最後一個對象將被添加到數組列表。這就是爲什麼你只得到最後一個記錄 – playmaker420