使用 XmlSlurper 或 XmlParser 更改 xml element/tag 名称
Change xml element/tag name using XmlSlurper or XmlParser
我有一个 xml 看起来像这样
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Samples>
<Sample>
<Name>
Sample1
</Name>
<Date>
01/20/2016
</Date>
</Sample>
</Samples>
我只想将标签名称从 "Samples" 更改为 "SampleList"。我该怎么做?
replaceNode
可用于重命名节点,如下所示:
def xml = '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Samples>
<Sample>
<Name>
Sample1
</Name>
<Date>
01/20/2016
</Date>
</Sample>
</Samples>
'''
def result = new XmlSlurper().parseText(xml)
result.replaceNode {
'SampleList' it.children()
}
groovy.xml.XmlUtil.serialize(result)
replaceNode
将闭包作为委托给构建器的方法参数。特别是在这种情况下,节点被替换而不是将其附加到主文档。 'SampleList' it.children()
类似于 'SampleList(it.children())'
。
解析 xml 的根元素是 Samples
(需要替换),replaceNode
直接在 result
上完成。
我有一个 xml 看起来像这样
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Samples>
<Sample>
<Name>
Sample1
</Name>
<Date>
01/20/2016
</Date>
</Sample>
</Samples>
我只想将标签名称从 "Samples" 更改为 "SampleList"。我该怎么做?
replaceNode
可用于重命名节点,如下所示:
def xml = '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Samples>
<Sample>
<Name>
Sample1
</Name>
<Date>
01/20/2016
</Date>
</Sample>
</Samples>
'''
def result = new XmlSlurper().parseText(xml)
result.replaceNode {
'SampleList' it.children()
}
groovy.xml.XmlUtil.serialize(result)
replaceNode
将闭包作为委托给构建器的方法参数。特别是在这种情况下,节点被替换而不是将其附加到主文档。 'SampleList' it.children()
类似于 'SampleList(it.children())'
。
解析 xml 的根元素是 Samples
(需要替换),replaceNode
直接在 result
上完成。