java - xpath - pom.xml
次のpom.xmlファイルをxml domリソースとして使用して<version>
います。コードを反復せずにタグの値を取得したいので、xpathを使用していますが、xpathエクスプレスが正しくないと思うため、値が返されません。助けていただければ幸いです。
Java コード
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("C:\\projects\\pom.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("project/version");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dc.app</groupId>
<artifactId>rum</artifactId>
<packaging>war</packaging>
<version>12.54-SNAPSHOT</version>
<name>rum</name>
<description>rum</description>
</project>