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

qyyhg6bp  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(171)
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>

谢谢

pbossiut

pbossiut1#

希望这就是你想要的。

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() ) )

相关问题