Java XPath:获取与查询匹配的所有元素

时间:2012-05-24 09:37:11

标签: java xml xpath namespaces xml-namespaces

我想对此XML文件进行XPath查询(摘录显示):

<?xml version="1.0" encoding="UTF-8"?>
<!-- MetaDataAPI generated on: Friday, May 25, 2007 3:26:31 PM CEST -->
<Component xmlns="http://xml.sap.com/2002/10/metamodel/webdynpro" xmlns:IDX="urn:sap.com:WebDynpro.Component:2.0" mmRelease="6.30" mmVersion="2.0" mmTimestamp="1180099591892" name="MassimaleContr" package="com.bi.massimalecontr" masterLanguage="it">
...
    <Component.UsedModels>
        <Core.Reference package="com.test.test" name="MasterModel" type="Model"/>
        <Core.Reference package="com.test.massimalecontr" name="MassimaleModel" type="Model"/>
        <Core.Reference package="com.test.test" name="TravelModel" type="Model"/>
    </Component.UsedModels>
...

我正在使用这段代码:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document document = builder.parse(new File("E:\\Test branch\\test.wdcomponent"));
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();

xpath.setNamespaceContext(new NamespaceContext() {
...(omitted)

System.out.println(xpath.evaluate(
    "//d:Component/d:Component.UsedModels/d:Core.Reference/@name", 
    document));

我期待得到的东西:

MasterModel
MassimaleModel
TravelModel

我得到了什么:

MasterModel

似乎只返回第一个元素。如何获得与我的查询匹配的所有匹配项?

2 个答案:

答案 0 :(得分:21)

您将获得NodeList

类型的项目
XPathExpression expr = xpath.compile("//Core.Reference");
NodeList list= (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < list.getLength(); i++) {
    Node node = list.item(i);
    System.out.println(node.getTextContent());
    // work with node

答案 1 :(得分:3)

请参阅How to read XML using XPath in Java

根据该示例,如果您首先编译XPath表达式然后执行它,指定您想要返回NodeSet,您应该得到您想要的结果。