3
votes

Can somebody help me find the mistake I am doing in evaluating following XPath expression?
I want to get all "DataTable" nodes under the node "Model" in my xml through XPath.
Here is my XML doc:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
  <Application>
    <Model>
      <DataSet name="ds" primaryTable="Members" openRows="1">
        <DataTable name="Members" openFor="write">
          <DataColumn name="id" type="String" mandatory="true" primaryKey="true" valueBy="user"/>
          <DataColumn name="name" type="String" mandatory="true" valueBy="user"/>
          <DataColumn name="address" type="String" mandatory="false" valueBy="user"/>
          <DataColumn name="city" type="String" mandatory="false" valueBy="user"/>
          <DataColumn name="country" type="String" mandatory="false" valueBy="user"/>
        </DataTable>
      </DataSet>
    </Model>
    <View>
      <Composite>
        <Grid>
          <Label value="ID:" row="0" column="0" />
          <Label value="Name:" row="1" column="0" />
          <Label value="Address:" row="2" column="0" />
          <Label value="City:" row="3" column="0" />
          <Label value="Country:" row="4" column="0" />

          <TextField name="txtId" row="0" column="1" />
          <TextField name="txtName" row="1" column="1" />
          <TextField name="txtAddress" row="2" column="1" />
          <TextField name="txtCity" row="3" column="1" />
          <TextField name="txtCountry" row="4" column="1" />
        </Grid>
      </Composite>
    </View>
  </Application>
</Root>

Here the Java code to extract required node list:

try {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    domFactory.setIgnoringComments(true);
    domFactory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document dDoc = builder.parse("D:\TEST\myFile.xml");

    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nl = (NodeList) xpath.evaluate("//Model//DataTable", dDoc, XPathConstants.NODESET);
    System.out.println(nl.getLength());

}catch (Exception ex) {
    System.out.println(ex.getMessage());
}

There is no problem in loading and parsing xml file and I can see correct nodes in dDoc. Problem is with xpath that returns nothing on evaluating my expression. I tried many other expressions for testing purpose but every time resulting NodeList "nl" does not have any item

1
Good question (+1). See my answer for more information and a hint about the cause of the problem.Dimitre Novatchev

1 Answers

2
votes

Most probably the XML document has a default namespace, which you didn't show.

The provided XPath expression selects the <DataTable> element when applied on the provided XML document.