2012-05-24 62 views
11

我想就這個XML文件的XPath查詢的元素(可顯示摘錄):的Java的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 

看來只有第一個元素被返回。我如何獲得與我的查詢匹配的所有匹配項?

+0

你可以試試這個'// d:Component/d:Component.UsedModels/@ name'並不能確定它在java中的工作。它在Python中工作。 :) – Bob

回答

20

你會得到類型的項目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 
3

How to read XML using XPath in Java

按照這個例子,如果你先編譯然後XPath表達式執行它,指定你想有一個節點集支持你應該得到你想要的結果。