我有这样的XML
<reg>
<user>
<Name> abc</Name>
<Email> abc@xyz.com</Email>
<picture> sdCard/imges.145.jpg </Picture>
<Date> 12/12/2012</Date>
</user>
<user>
<Name> abc dfg</Name>
<Email> ertdg@xyz.com</Email>
<picture> sdCard/imges.145.jpg </Picture>
<Date> 23/12/2013</Date>
</user>
</reg>
我想获取特定节点的值并将它们添加到ArrayList以在ListView中显示 我试过这段代码,但它只给出了Last Record
的值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);
如何让它显示所有记录?
答案 0 :(得分:1)
您的代码仅为评论中的@playmaker420解释了Last Record的值。要解决此问题,您可以尝试循环遍历<user>
元素,而不是分别遍历每个<name>
,<email>
,<picture>
和<date>
:
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/reg/user";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Users setUser = new Users();
Element el = (Element) nodeList.item(i);
String name = el.getElementsByTagName("Name").item(0).getTextContent();
setUser.setName(name);
String email = el.getElementsByTagName("Email").item(0).getTextContent();
setUser.setEmail(email);
String picture = el.getElementsByTagName("picture").item(0).getTextContent();
setUser.setimage(picture);
String date = el.getElementsByTagName("Date").item(0).getTextContent();
setUser.setDate(date);
uData.add(setUser);
}