次のコードを実行すると、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]