当xml文档中有一个或多个namespace时,用xpath获取不到节点。此时 需要手动设置namespace。例如:需要修改pom.xml中的artifactid。
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>mygroupId</groupId>
<artifactId>myartifactId</artifactId>
<packaging>maven-plugin</packaging>
<version>1.0.0</version>
<name>xxx</name>
<url>http://maven.apache.org</url>
</project>
Document document = null;
Map namespace = null;
try {
document = XmlUtils.getXmlDocment("/server_pom.xml");
if(document == null){
return;
}
namespace = new HashMap();
// 获得命名空间
String nsURI = document.getRootElement().getNamespaceURI();
namespace.put("xmlns",nsURI);
XPath xpath_artifactId = document.createXPath("//xmlns:project/xmlns:artifactId");
// 设置artifactId
document = XmlUtils.setXmlNode(document,namespace,xpath_artifactId,projectName + "Server");
} catch (Exception e) {
e.printStackTrace();
}
public static Document setXmlNode(Document document, Map namespace, XPath xpath, String nodeText) throws Exception{
if(document == null || namespace== null|| namespace.isEmpty()){
return null;
}
// 创建解析路径,就是在普通的解析路径前加上map里的key值
// 解决xpath在有命名空间情况下获取不到就节点问题
xpath.setNamespaceURIs(namespace);
Node artifactIdNode = xpath.selectSingleNode(document);
if(artifactIdNode != null){
// 修改artifactId
artifactIdNode.setText(nodeText);
}else{
throw new Exception(xpath + "节点为空!");
}
return document;
}