在Java中评估XPath表达式的问题

时间:2010-06-05 18:20:01

标签: java xpath

有人可以帮我找到我在评估XPath表达式时所犯的错误吗? 我希望通过XPath在我的xml节点“Model”下获得所有“DataTable”节点 这是我的XML文档:

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

这里是提取所需节点列表的Java代码:

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

加载和解析xml文件没有问题,我可以在dDoc中看到正确的节点。问题在于xpath在评估我的表达式时没有返回任何内容。我尝试了许多其他表达式用于测试目的,但每次生成NodeList“nl”都没有任何项目

1 个答案:

答案 0 :(得分:2)

很可能XML文档有一个默认命名空间,您没有显示。

提供的XPath表达式在提供的 XML文档上应用时会选择<DataTable>元素