我希望使用groovy将xml转换为JSON.我理解转换的细节取决于我的偏好,但有人可以推荐我应该使用哪些库和方法,并向我提供一些关于为什么/如何使用它们的信息?我正在使用groovy,因为我被告知它是一个非常有效的解析器,所以我正在寻找将利用这个的库
谢谢!
解决方法
您可以使用基本的Groovy完成所有操作:
// Given an XML string def xml = '''<root> | <node>Tim</node> | <node>Tom</node> |</root>'''.stripMargin() // Parse it def parsed = new XmlParser().parseText( xml ) // Convert it to a Map containing a List of Maps def jsonObject = [ root: parsed.node.collect { [ node: it.text() ] } ] // And dump it as Json def json = new groovy.json.JsonBuilder( jsonObject ) // Check it's what we expected assert json.toString() == '{"root":[{"node":"Tim"},{"node":"Tom"}]}'
但是,你真的需要考虑某些事情……
>您将如何表示属性?
>您的XML是否包含< node> text< another> woo< / another> text< / node>样式标记?如果是这样,你将如何处理?
> CDATA?注释?等等?
它不是两者之间平滑的1:1映射……但对于给定的特定格式的XML,可能会提出给定的特定格式的Json.
更新:
要从文档中获取名称(请参阅注释),您可以执行以下操作:
def jsonObject = [ (parsed.name()): parsed.collect { [ (it.name()): it.text() ] } ]
更新2
您可以添加更深入的支持:
// Given an XML string def xml = '''<root> | <node>Tim</node> | <node>Tom</node> | <node> | <anotherNode>another</anotherNode> | </node> |</root>'''.stripMargin() // Parse it def parsed = new XmlParser().parseText( xml ) // Deal with each node: def handle handle = { node -> if( node instanceof String ) { node } else { [ (node.name()): node.collect( handle ) ] } } // Convert it to a Map containing a List of Maps def jsonObject = [ (parsed.name()): parsed.collect { node -> [ (node.name()): node.collect( handle ) ] } ] // And dump it as Json def json = new groovy.json.JsonBuilder( jsonObject ) // Check it's what we expected assert json.toString() == '{"root":[{"node":["Tim"]},{"node":["Tom"]},{"node":[{"anotherNode":["another"]}]}]}'
同样,所有先前的警告仍然适用(但此时应该听到更大声);-)