【发布时间】:2018-02-09 21:14:13
【问题描述】:
我正在使用 Dom4J 解析一些 Maven Pom 文件。当我使用没有默认命名空间的 Pom 文件时,一切正常。例如:
Document pom = DocumentHelper.parseText(
"<project>" +
" <groupId>xx.gov.xxx.sistema.xxx</groupId>" +
" <artifactId>sis-teste</artifactId>" +
" <packaging>war</packaging>" +
"</project>");
//below works fine
String groupId = pom.selectSingleNode("/project/groupId").getText()
但如果我的 Pom 文件定义了默认命名空间,它就会停止工作:
Document pom = DocumentHelper.parseText(
"<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/maven-v4_0_0.xsd\">" +
" <groupId>xx.gov.xxx.sistema.xxx</groupId>" +
" <artifactId>sis-teste</artifactId>" +
" <packaging>war</packaging>" +
"</project>");
//NullPointerException!!!!!!!!!!!!!!!!!!!!
String groupId = pom.selectSingleNode("/project/groupId").getText()
奇怪的是pom.selectSingleNode("/project") 工作正常。
如何让我的 xpath 查询使用默认命名空间?我只想查询 "/project/groupId" 并获取 groupId 节点。
【问题讨论】:
-
如果您不想更改您的查询,您将需要深入 XPath 中命名空间的兔子洞。我建议你阅读这个edankert.com/defaultnamespaces.html
标签: xpath xml-namespaces dom4j