开发者

Problem with evaluating XPath expression in Java

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.setIgnoringElementConte开发者_如何学PythonntWhitespace(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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜