如何在XML文件中找到最大的属性值?

时间:2018-01-05 12:05:42

标签: java xml xpath

我正在尝试创建一个能够在XML文件中打印出属性的最大值的小程序。我写了以下代码:

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());

}

}

XML文件看起来像这样。

<?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>

运行程序时出现NullPointerException错误。我试图找到最大的LOG值然后打印出来。我认为我在Xpath中的查询是不正确的。可以任何人帮我修复这个查询和NullPointerException错误。

1 个答案:

答案 0 :(得分:0)

XPath 2.0

这个XPath,

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

将选择具有最大Log属性值的@LOG元素。

XPath 1.0

这个XPath,

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

将选择具有最大Log属性值的@LOG元素。