Gradle使用groovy XML解析器解析XML文件,例如,
<foo id="3">
<!-- this is bar -->
<bar id="5"
attr1="10">
attr2="20">
<hello>world</hello>
</bar>
<foo>
解析xml并将其写出:
def root = new XmlParser().parse(new FileInputStream("/foo.xml"))
// add some nodes
groovy.xml.XmlUtil.serialize(root, new FileOutputStream("/bar.xml"))
所有注释和换行符都消失了。
如何使用groovy XML解析器保留注释和所有其他格式?
我看了看这个:
Groovy edit XML file, keep comments, line breaks
如何导入groovy.xml。*?在gradle中无法识别groovy。
最佳答案
您应该使用jdom2,它将解决您的问题
首先,在build.gradle
文件中设置依赖项
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.jdom:jdom2:2.0.6'
}
}
然后使用此修改后的代码段:
def root = new org.jdom2.input.SAXBuilder().build(new FileInputStream("/tmp/foo.xml"))
// add some nodes
new org.jdom2.output.XMLOutputter().with {
format = org.jdom2.output.Format.getRawFormat()
format.setLineSeparator(org.jdom2.output.LineSeparator.NONE)
output(root, new FileOutputStream("/tmp/bar.xml"))
}
关于xml - Gradle Groovy如何在XML解析器中保留注释和所有格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45037594/