Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java XPath: Get all the elements that match a query

I want to make an XPath query on this XML file (excerpt shown):

<?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>
...

I'm using this snippet of code:

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));

What I'm expecting to get:

MasterModel
MassimaleModel
TravelModel

What I'm getting:

MasterModel

It seems that only the first element is returned. How can I get all the occurrences that matches my query?

like image 263
Pietro M. Avatar asked May 24 '12 09:05

Pietro M.


People also ask

Which XPath function is used to extract all the elements which matches a particular text value?

Using the XPath contains() function, we can extract all the elements on the page that match the provided text value.

What is XPath parsing?

It defines a language to find information in an XML file. It is used to traverse elements and attributes of an XML document. XPath provides various types of expressions which can be used to enquire relevant information from the XML document.


2 Answers

You'll get a item of type 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
like image 195
Christian Kuetbach Avatar answered Oct 16 '22 16:10

Christian Kuetbach


See How to read XML using XPath in Java

As per that example, If you first compile the XPath expression then execute it, specifying that you want a NodeSet back you should get the result you want.

like image 33
Jon Payne Avatar answered Oct 16 '22 15:10

Jon Payne