1

I am trying to create a small program that is able to print out the largest value of a attribute in an XML file. I have wrote the following code:

public class GetMaxLog {
    public static void main(String[] args) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true); 
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = (Document)builder.parse("FILE");

    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();

    XPathExpression expr = xpath.compile("//PasswordVault/User[@id = 1]//Log[not(@LOG < ../Log/@LOG)]/LOG/text()");

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;     

  //returns the element at tag value 0 thus only the first set of data    
    System.out.println(nodes.item(0).getNodeValue());

}

}

And the XML file looks like this.

<?xml version="1.0" encoding="UTF-8"?>
<PasswordVault>
  <User id="1">
    <Log LOG="1">
      <AccountType>afsdgsd</AccountType>
      <Username>asdas</Username>
      <Password>dsgsdg</Password>
      <E-mail>aadfaf</E-mail>
    </Log>
    <Log LOG="10">
      <AccountType>afsdgsd</AccountType>
      <Username>asdas</Username>
      <Password>dsgsdg</Password>
      <E-mail>aadfaf</E-mail>
    </Log>
  </User>
</PasswordVault>

There is a NullPointerException error when i run the program. I am trying to find the largest LOG value and then print it out.I think that my query within Xpath is incorrect .Could anyone help me fix this query and the NullPointerException error also.

Harsh
  • 25
  • 5

1 Answers1

0

XPath 2.0

This XPath,

//Log[@LOG = max(//Log/@LOG)]

will select the Log elements with the maximum @LOG attribute value.

XPath 1.0

This XPath,

//Log[not(../Log/@LOG > @LOG)]

will select the Log elements with the maximum @LOG attribute value.

kjhughes
  • 106,133
  • 27
  • 181
  • 240