为什么xPath查询没有返回正确的输出?

时间:2018-01-07 16:20:18

标签: java xml xpath

我的XML文件的布局是:

<?xml version="1.0" encoding="UTF-8"?>
<PasswordVault>
  <User id="1">
    <Log LOG="1">
      <AccountType>asd</AccountType>
      <Username>asd</Username>
      <Password>asd</Password>
      <E-mail>asd</E-mail>
    </Log>
    <Log Log="3">
      <AccountType>as</AccountType>
      <Username>as</Username>
      <Password>as</Password>
      <E-mail>as</E-mail>
    </Log>
  </User>
</PasswordVault>

我编写了java代码:

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

        String y = x();
        System.out.println(y);

    }
    public static String x() throws Exception{  
        try {
            DocumentBuilderFactory factory = 
               DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true); 
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = (Document)builder.parse("FILE PATH");

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

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

            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    
           return  nodes.item(0).getNodeValue();
        }catch(SAXParseException e){
            return "0";
        }
    }
 }

当最大日志值明显为3时,该函数始终返回1.如何修复此函数以始终输出最大日志值。

1 个答案:

答案 0 :(得分:0)

XML名称区分大小写。 @LOG的最大值为1.要解决您遇到的问题,请从

更改数据文件
<Log Log="3">

<Log LOG="3">