java - xpath - pom.xml
我正在使用以下 pom.xml 文件作为 xml dom 资源,我想在<version>
不迭代代码的情况下获取标记的值,这就是我使用 xpath 的原因,但我猜我的 xpath express 不正确,这就是它没有返回任何值的原因。任何帮助表示赞赏。
爪哇代码
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>