Groovy
中, 自带了xml
处理的相关类, 操作起来也是相当nice的.
本文操作实例在Android
开发环境中进行.
测试的xml文件:
def targetFile = new File("${buildFile.parent}/src/main/res/values/strings.xml")
def testFile = new File("${buildFile.parent}/src/main/res/values/strings_test.xml")
def afterFile = new File("${buildFile.parent}/src/main/res/values/strings_after.xml")
groovy.util.XmlSlurper
groovy.util.XmlParser
XmlSlurper
这个类, 在读取xml
文件方面, 相当方便.
可以直接使用xml
文件中的tag名
,直接读取对应的值
XmlParser
这个类, 在修改xml
文件方面, 相当方便.
各种操作的api
都有方法.
/**
*
* 获取一个 GPathResult 对象
* @see groovy.util.slurpersupport.GPathResult
* */
static def openXml(xml) {
def xmlSlurper = new XmlSlurper()
def result = xmlSlurper.parse(xml)
return result
}
static def openXmlText(xmlText) {
def xmlSlurper = new XmlSlurper()
def result = xmlSlurper.parseText(xmlText)
return result
}
static def getValue(pathResult, key) {
return getNodeChildren(pathResult, key)[0].text()
}
/**
* 获取属性名为 name 值为 key 的 Node
* */
static def getNodeChildren(pathResult, key) {
pathResult?.depthFirst()?.findAll { node ->
if (node["@name"] == key) {
return node
}
}
}
/**
* @return 返回修改之前的值
* */
static def setValue(pathResult, key, value) {
def nodeChildren = getNodeChildren(pathResult, key)
def oldValue = nodeChildren[0].text()
nodeChildren[0].replaceBody(value)
return oldValue
}
/**
* XmlSlurper 实在是没有找到 删除 node 的方法.
* 所以, 这里使用 XmlParser 删除了 node,
* 再重新返回 GPathResult 对象
*
* @see groovy.util.XmlSlurper
* @see groovy.util.XmlParser
* */
static def deleteKey(pathResult, key) {
def xmlText = groovy.xml.XmlUtil.serialize(pathResult)
def xmlParser = new groovy.util.XmlParser()
def rootNode = xmlParser.parseText(xmlText)
def deleteNode = null
rootNode.depthFirst().each {
//println "tag:${it.name()} name:${it.attributes()["name"]} value:${it.value()} childs:${it.children.size()}"
if (it.attributes()["name"] == key) {
deleteNode = it
}
}
deleteNode?.parent()?.remove(deleteNode)
def afterXmlText = groovy.xml.XmlUtil.serialize(rootNode)
return openXmlText(afterXmlText)
}
/**
* @see #deleteKey
*
* */
static def addKey(pathResult, key, value) {
def xmlText = groovy.xml.XmlUtil.serialize(pathResult)
def xmlParser = new groovy.util.XmlParser()
def rootNode = xmlParser.parseText(xmlText)
def targetNode = null
rootNode.depthFirst().each {
//println "tag:${it.name()} name:${it.attributes()["name"]} value:${it.value()} childs:${it.children.size()}"
if (it.name() == "resources") {
targetNode = it
}
}
targetNode?.append(new groovy.util.Node(null, "string", ["name": key], value))
def afterXmlText = groovy.xml.XmlUtil.serialize(rootNode)
return openXmlText(afterXmlText)
}
/**
* 保存到指定文件
* */
static def save(targetFile, xml) {
def text = null
if (xml instanceof groovy.util.slurpersupport.GPathResult) {
text = groovy.xml.XmlUtil.serialize(xml)
} else {
text = xml.toString()
}
def tempFile = null
if (targetFile instanceof File) {
tempFile = targetFile
} else {
tempFile = new File(targetFile)
}
tempFile.withWriter("UTF8") { writer ->
writer.write(text)
}
}
def stringWrite = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(stringWrite)
builder.resources() {
'string'(name: "app_name", name2: "app_name_2", "test_value1")
'string'(name: 'app_name2', 'test_value2')
}
def xmlText = stringWrite.toString()
def targetFile = new File("${buildFile.parent}/src/main/res/values/styles.xml")
gradle.projectsEvaluated {
def rootNode = openXml(targetFile)
println "......xml......"
println rootNode.name()
if ("resources" == rootNode.name()) {
//确保根节点是 resources
//去重后的 nodes
def resultNodes = [:]
//需要删除的 nodes
def deleteNodes = []
rootNode.children().each {
//name 属性的值
def name = it.attributes()["name"]
def node = resultNodes[name]
if (node != null) {
println "找到重复属性, name为 ${name}"
deleteNodes += node
} else {
println "新增节点, name为 ${name}"
resultNodes[name] = it
}
//println it.name() + it.attributes()["name"]
}
println 'xml...原内容'
logXmlText(rootNode)
def childs = rootNode.children()
for (int i = childs.size() - 1; i >= 0; i--) {
rootNode.remove(childs[i])
}
println 'xml...去重后'
resultNodes.each { _, node ->
rootNode.append(node)
}
logXmlText(rootNode)
save(targetFile, rootNode)
}
}
static def openXml(xml) {
def xmlParser = new groovy.util.XmlParser()
def result = xmlParser.parse(xml)
return result
}
static def openXmlText(xmlText) {
def xmlParser = new groovy.util.XmlParser()
def result = xmlParser.parseText(xmlText)
return result
}
static def logXmlText(node) {
def xmlText = groovy.xml.XmlUtil.serialize(node)
println xmlText
}
/**
* 保存到指定文件
* */
static def save(targetFile, xml) {
def text = null
if (xml instanceof groovy.util.slurpersupport.GPathResult ||
xml instanceof groovy.util.Node) {
text = groovy.xml.XmlUtil.serialize(xml)
} else {
text = xml.toString()
}
def tempFile = null
if (targetFile instanceof File) {
tempFile = targetFile
} else {
tempFile = new File(targetFile)
}
//println "保存:$targetFile"
//println "保存:$text"
tempFile.withWriter("UTF8") { writer ->
writer.write(text)
}
}
DSL源码参考 推荐阅读
群内有各(pian)种(ni)各(jin)样(qun)
的大佬,等你来撩.
点此快速加群
请使用QQ扫码加群, 小伙伴们都在等着你哦!
关注我的公众号, 每天都能一起玩耍哦!