xml到Groovy中的json转换 [英] xml to json conversion in Groovy

查看:311
本文介绍了xml到Groovy中的json转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助将Groovy中的xml转换为json。我有这样的XML是这样的

  def xmlrecords ='''< root> 
< node1> abc< / node1>
< node2> def< / node2>
< node3> hij< / node3>
< / root>'''

我知道这很简单,但我正在努力克服常规。因此,任何帮助将非常感激。



谢谢。


$ b

更新



我知道我可以做一些像

  def xml = new XmlParser()。parseText(xmlrecords)
def json = new JsonBuilder()

json.records
{
node1abc
node2def
node3hij
}

println json.toPrettyString()

但我想要做的是访问像这样的节点的数据
$ b

  json.records 
{
node1 xml.node1 //xml.node1=abc
node2 xml.node2
node3 xml.node3
}

因为每个节点存储的数据一直在为我改变。无论我上面写的任何代码是行不通的,我一直在为此而头痛。所以你能帮我一下吗?

解决方案

你几乎在正确的轨道上。您只需要在您的xml对象上应用 .text()函数。

见下面

  static main(args){

def xmlrecords ='''< root>
< node1> abc< / node1>
< node2> def< / node2>
< node3> hij< / node3>
< / root>'''

def xml = new XmlParser()。parseText(xmlrecords)
def json = new JsonBuilder()

json.records
{
node1 xml.node1.text()//xml.node1=abc
node2 xml.node2.text()
node3 xml.node3.text ()
}

println json.toPrettyString()
}

输出

  {
records:{
node1:abc,
node2:def,
node3:hij
}
}

希望这有助于您!

I need help with converting an xml to json in Groovy. The xml I have is something like this

 def xmlrecords = '''<root>
                        <node1>abc</node1>
                        <node2>def</node2>
                        <node3>hij</node3>
                        </root>'''

I know this is fairly simple, but I'm struggling to get to grips with groovy. So any help would be very much appreciated.

Thanks.

UPDATE

I know that I can do something like

def xml= new XmlParser().parseText( xmlrecords )
def json = new JsonBuilder()

json.records
{
   node1 "abc"
   node2 "def"
   node3 "hij"
}

println json.toPrettyString()

but what I want to do is access the data of the nodes like this

json.records
    {
       node1 xml.node1   //xml.node1=abc
       node2 xml.node2
       node3 xml.node3
    }

since the data that each node stores keeps changing for me. Whatever code that I have written above doesn't work and I have been breaking my head over this. So Could you please help me out?

解决方案

You're pretty much on the right track. You just needed to apply the .text() function on your xml object.

See below

static main(args) {

    def xmlrecords = '''<root>
                    <node1>abc</node1>
                    <node2>def</node2>
                    <node3>hij</node3>
                    </root>'''

    def xml= new XmlParser().parseText(xmlrecords)
    def json = new JsonBuilder()

    json.records
    {
       node1 xml.node1.text()  //xml.node1=abc
       node2 xml.node2.text()
       node3 xml.node3.text()
    }

    println json.toPrettyString()
}

Output

{
"records": {
    "node1": "abc",
    "node2": "def",
    "node3": "hij"
    }
}

Hope this helps!

这篇关于xml到Groovy中的json转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆