I have a XML file like this :

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<user>
    <account phone ="2000">         
    </account>
</user>
<user>
    <account phone ="2001">         
    </account>
</user>
<user>
    <account phone ="2002">         
    </account>
</user>
<user>
    <account phone ="2003">         
    </account>
</user>

From java code, i want to get latest phone attribute . I'm not using condition that attr.getValue() because this data always updated, so I want to get the latest value of phone attribute.

link|flag

2 Answers

You can use the following xpath to get the last user's phone attribute:

//user[last()]/account/@phone

This will give you you phone ="2003".

Here is a java snippet:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;   

XPath xpath = XPathFactory.newInstance().newXPath();
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("input.xml");
String phone = xpath.evaluate("//user[last()]/account/@phone", doc);
System.out.println(phone);
link|flag

Assuming that you parse the xml into a org.w3c.dom.Document then the following should work:

Document doc = parse(xml);

ItemList accounts= doc.getElementsByTagName("account");
Element lastAccount = accounts.item(accounts.getLength()-1);    
String phone = lastAccount.getAttribute("phone");
link|flag

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.