当我运行以下代码时,我得到输出Left:
而不是Left: 16
.
// Retrieve DOM from XML file
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
Document dom = null;
try {
db = dbf.newDocumentBuilder();
dom = db.parse("config");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
try {
String left = (String) xPath.evaluate(
"/settings/boundaries[0]/left[0]", dom,
XPathConstants.STRING);
System.out.println("Left: " + left);
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这是XML文件
<settings>
<boundaries>
<left>16</left>
<right>301</right>
<bottom>370</bottom>
<top>171</top>
</boundaries>
</settings>
编辑:根据答案,这应该有效,但它没有:
// Retrieve DOM from XML file
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
Document dom = null;
try {
db = dbf.newDocumentBuilder();
dom = db.parse("config");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
try {
String left = (String) xPath.evaluate(
"/settings/boundaries[0]/left[0]/text()", dom,
XPathConstants.STRING);
System.out.println("Left: " + left);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
另请注意,此代码,
Element el = (Element) dom.getDocumentElement()
.getElementsByTagName("boundaries").item(0);
System.out.println(el.getElementsByTagName("left").item(0));
印刷[left: null]