在JAXP中使用XPath检索XML节点和节点属性的值

时间:2010-12-24 06:19:04

标签: java xml xpath jaxp

给出一个如下所示的xml文档:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="agentType">STANDARD</entry>
    <entry key="DestinationTransferStates"></entry>
    <entry key="AgentStatusPublishRate">300</entry>
    <entry key="agentVersion">f000-703-GM2-20101109-1550</entry>
    <entry key="CommandTimeUTC">2010-12-24T02:25:43Z</entry>
    <entry key="PublishTimeUTC">2010-12-24T02:26:09Z</entry>
    <entry key="queueManager">AGENTQMGR</entry>
</properties>

我想打印“key”属性和元素的值,使它看起来像这样:

agentType = STANDARD
DestinationTransferStates = 
AgentStatusPublishRate = 300
agentVersion = f000-703-GM2-20101109-1550
CommandTimeUTC = 2010-12-24T02:25:43Z
PublishTimeUTC = 2010-12-24T02:26:09Z
queueManager = AGENTQMGR

使用此代码我可以毫无问题地打印节点值:

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//properties/entry/text()");

Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getNodeValue()); 
}

我可以通过更改xpath表达式和节点方法来打印“key”属性的值,如下所示:

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//properties/entry");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getAttributes().getNamedItem("key").getNodeValue()); 
}

似乎有办法在单个evaluate中获取这两个值。我总是可以评估两个NodeLists并使用一个公共索引迭代它们,但我不确定它们是否保证以相同的顺序返回。任何建议表示赞赏。

1 个答案:

答案 0 :(得分:11)

getTextContent()怎么样?这应该做的工作。

Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++)
{
    Node currentItem = nodes.item(i);
    String key = currentItem.getAttributes().getNamedItem("key").getNodeValue();
    String value = currentItem.getTextContent();

    System.out.printf("%1s = %2s\n", key, value);
}

有关详细信息,请参阅getTextContent()的javadoc。我希望这会对你有所帮助。