有人能幫我找到我在評估以下XPath表達式時所犯的錯誤嗎?
我想通過XPath在我的xml中獲取節點「Model」下的所有「DataTable」節點。
這裏是我的XML文檔:在Java中評估XPath表達式的問題
<?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)。查看我的答案以獲取更多信息並提供有關問題原因的提示。 – 2010-06-05 19:05:13