我想使用Groovy的XmlSlurper解析和修改Maven的pom.xml。我的pom.xml声明了命名空间xsi。为默认名称空间中的元素添加tag0名称空间
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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>a-group-id</groupId>
<artifactId>an-artifact-id</artifactId>
我的Groovy的来源如下:
import groovy.xml.XmlUtil
def pom = new XmlSlurper().parse('pom.xml')
.declareNamespace('': 'http://maven.apache.org/POM/4.0.0',
xsi: 'http://www.w3.org/2001/XMLSchema-instance')
//manipulate the pom
println XmlUtil.serialize(pom)
你可能注意到了,我宣布第一个命名空间为空。然而在输出tag0中无处不在。
<?xml version="1.0" encoding="UTF-8"?>
<tag0:project xmlns:tag0="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">
<tag0:modelVersion>4.0.0</tag0:modelVersion>
<tag0:groupId>a-group-id</tag0:groupId>
<tag0:artifactId>an-artifact-id</tag0:artifactId>
如何避免这种情况?
眼下我的解决方法是手动删除标签:
println XmlUtil.serialize(pom).replaceAll('tag0:', '').replaceAll(':tag0', '')
正在构建'XmlSlurper'没有名称空间支持godd够了吗?即:'println XmlUtil.serialize(new XmlSlurper(false,false).parse('pom.xml'))'? – 2012-02-09 14:14:39
哇,是的,这已经够了,谢谢蒂姆。你能把它作为答案吗?另外我注意到,XML中的所有注释都丢失了,您是否知道它的任何解决方法?顺便说一下,这里是我写的两个工具[pomRm](http://www.stefanolocati.it/blog/?p=1226)和[pomVersions](http://www.stefanolocati.it/blog/?p= 1220)。 – stivlo 2012-02-09 14:51:08
目前无法看到如何保留评论... :-(如果我今天下午得到空闲时刻,我会想一想... – 2012-02-09 15:15:39