[英]Groovy - Modify xml file value
I have an XML file and I am pasting my xml file below.我有一个 XML 文件,我正在下面粘贴我的 xml 文件。 I want to change the value of splash_color using a groovy script.我想使用 groovy 脚本更改 splash_color 的值。 I have tried to parse it but not able to succeed.我试图解析它但无法成功。 XML XML
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="splash_color">#D3B61A</color>
</resources>
Groovy Code:常规代码:
def xmlFile = "$androidWorkingDirPath/app/src/main/res/values/colors.xml"
def xml = new XmlParser().parse(xmlFile)
xml.color[0].each {
//it.@name = "test2"
//it.value = "test2"
println("it.value=$it.value")
println("it.value=$it.value.name")
}
new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile))).println("Xmlvalue=$xml")
The below works.下面的作品。
def xmlFile = '''<?xml version="1.0" encoding="UTF-8"?>
<resources>
<color name="splash_color">#D3B61A</color>
</resources>
'''
You can use XmlUtil.serialize
instead of new XmlNodePrinter(new PrintWriter(new FileWriter
...您可以使用XmlUtil.serialize
而不是new XmlNodePrinter(new PrintWriter(new FileWriter
...
import groovy.xml.XmlUtil
I'm using parseText()
because in this example I'm not reading from a file我使用parseText()
因为在这个例子中我没有从文件中读取
def resources = new XmlParser().parseText(xmlFile)
You don't have to use [0]
here, but if there are more nodes with the same name, use findAll()此处不必使用[0]
,但如果同名节点较多,则使用findAll()
resources.color.each {
Use ${}
to interpolate variables in strings使用${}
在字符串中插入变量
println "it.value=${it.value}"
println "it.name=${it.@name}"
}
println XmlUtil.serialize(resources)
You can pipe that to a file.您可以将其通过管道传输到文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.