使用groovy将传入的XML转换为密钥对XML


Can you please help me convert incoming XML to key value XML using groovy for eg? 

请参考下面的示例进行转换。该示例仅包含两个字段,但实际上可能包含许多字段

<root>
<FirstName>John</FirstName>
<LastName>Major</LastName>
</root>

to 
<root>
<row>
<Key>FirstName</Key>
<Value>John</Value>
</row>
<row>
<Key>LastName</Key>
<Value>Major</Value>
</row>
</root>

感谢

希望这就是你想要的。

import groovy.xml.MarkupBuilder
import groovy.xml.XmlSlurper
import groovy.xml.XmlUtil
def startingXmlTxt =
'''<root>
<FirstName>John</FirstName>
<LastName>Major</LastName>
</root>'''
def startingXml = new XmlSlurper().parseText(startingXmlTxt)
def sw = new StringWriter()
def bldr = new MarkupBuilder(sw)
bldr.root {
startingXml.'*'.each { aRt ->
row {
Key(aRt.name())
Value(aRt.text())
}
}
}
println XmlUtil.serialize( new XmlSlurper().parseText( sw.toString() ) )

然后回来。。。

startingXml = new XmlSlurper().parseText(sw.toString())
sw = new StringWriter()
bldr = new MarkupBuilder(sw)
bldr.root {
startingXml.'*'.each{ aRt ->
"${aRt.Key}"( aRt.Value )
}
}
println XmlUtil.serialize( new XmlSlurper().parseText( sw.toString() ) )

最新更新