我是新手。我的要求面临问题。
我的要求是将嵌套的XML转换为Json
下面是输入文件:
for($month = 1; $month<=ceil($amountPaid/$rent); $month++){
//For each month there is money for rent (using ceil() to account for fractions)
assignRentFunction(
$month,
// The number of the month
$rent
//Show the rent ($rent)
-
//Deduct
max(($month * $rent - $amountPaid),0)
//Any difference if the whole rent for that month hasn't been paid
/**
* This relies on a little hack with the max() function:
* max($var,0) will return 0 if $var is less than 0.
* So we check to see if the sum of rent up to that month ($month * $rent)
* is greater than what was paid ($month * $rent) - $amountPaid.
* If it isn't because it's wrapped in the max,
* the net (negative) number will just be shown as nill.
* If it is, the net positive number will be subtracted
* from the month's rent.
**/
);
}
首选输出如下:
<root>
<Account>
<name>name</name>
<age>age</age>
</Account>
<Assets>
<record>
<info>info</info>
<details>details</details>
<attributes>
<property>property</property>
</attributes>
</record>
<record>
<info>info 1</info>
<details>details 1</details>
<attributes>
<property>property 1</property>
</attributes>
</record>
</Assets>
</root>
在{
"root":[
{"account":
"records":{
{"name":"name","age":"age"}
}
},
{"assets":
"records":{
"info":"info","details":"details"
},
{"attributes":{"property":"property"}}
,
{
"info":"info 1","details 1":"details 1"
},
{"attributes":{"property":"property 1"}}
}
]
}
段中,我们将获得Assets
条记录,所有记录数据应填充在n
内部。
有什么办法可以做到这一点?
您的任何意见都会受到赞赏
答案 0 :(得分:0)
更新的代码:
import groovy.json.JsonBuilder
def text = '''
<root>
<Account>
<name>name</name>
<age>age</age>
</Account>
<Assets>
<record>
<info>info</info>
<details>details</details>
<attributes>
<property>property</property>
</attributes>
</record>
<record>
<info>info 1</info>
<details>details 1</details>
<attributes>
<property>property 1</property>
</attributes>
</record>
</Assets>
</root>
'''
def toJsonBuilder(xml){
new groovy.json.JsonBuilder(build(new XmlParser().parseText(xml)))
}
def build(node){
if (node instanceof String)
return
def map = [ "${node.name()}" : '' ]
if (!node.children().isEmpty() && !(node.children().get(0) instanceof String)) {
map.put("${node.name()}", node.children().collect{build(it)}.findAll{it != null})
} else if (node.text() != ''){
map.put("${node.name()}", node.text())
}
map
}
println toJsonBuilder(text).toPrettyString()