我正在尝试创建一个能够在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错误。
答案 0 :(得分:0)
这个XPath,
//Log[@LOG = max(//Log/@LOG)]
将选择具有最大Log
属性值的@LOG
元素。
这个XPath,
//Log[not(../Log/@LOG > @LOG)]
将选择具有最大Log
属性值的@LOG
元素。