Problem with evaluating XPath expression in Java

Posted by JSteve on Stack Overflow See other posts from Stack Overflow or by JSteve
Published on 2010-06-05T18:20:00Z Indexed on 2010/06/05 18:22 UTC
Read the original article Hit count: 270

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about java

Related posts about xpath