我正在尝试使用Groovy的XmlSlurper解析和修改Maven的pom.xml。我的pom.xml声明了名称空间xsi。
<?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
是否足够好?例如:println XmlUtil.serialize( new XmlSlurper( false, false ).parse( 'pom.xml' ) )
? - tim_yatesXmlParser
的东西,看起来它正朝着我们想要的方向发展,但是到目前为止还没有成功让它工作:-/ 不确定是解析问题还是序列化问题... - tim_yates