简体   繁体   English

XSLT等效于XML到JSON

[英]XSLT equivalent for XML to JSON

I have an application where I am parsing an XML document and want to translate it into a JSON document and embed that document directly into MongoDB. 我有一个应用程序,我正在解析XML文档,并希望将其转换为JSON文档并将该文档直接嵌入到MongoDB中。 Normally going from XML <-> XML I'd use a tool such as XSLT for the translation. 通常来自XML < - > XML我会使用XSLT等工具进行翻译。 Is there currently a decent tool to translate XML -> JSON? 目前是否有一个很好的工具来翻译XML - > JSON? Only has to be uni-directional. 只需要是单向的。 I won't be translating it back to XML anytime soon. 我不会很快将它翻译回XML。 I just want it formatted in a particular state that's embeddable into MongoDB for retrieval and representation to a serializer in the future. 我只是希望它以特定的状态格式化,可以嵌入到MongoDB中,以便将来检索和表示给序列化程序。

The best available tool for translating XML into JSON, either in general or for a particular vocabulary, is XSLT. XSLT是将XML转换为JSON的最佳工具,无论是一般还是特定词汇。 Use method="text" on your xsl:output element. 在xsl:output元素上使用method="text"

If you don't mind using ActiveSupport and Ruby Hash as intermediary: 如果您不介意使用ActiveSupport和Ruby Hash作为中介:

require 'active_support/core_ext'
Hash.from_xml(xml).to_json

Note that it would be pretty easy to manipulate the data when it is a Hash if you need to do so. 请注意,如果您需要这样做,那么在它是Hash时操作数据会非常容易。

Also, note that converting XML to a hash can be lossy (when it comes to namespaces and attributes). 另外,请注意,将XML转换为哈希可能是有损的(当涉及名称空间和属性时)。 If you care about this, you might check out other XML parsers (like Crack or CobraVsMongoose ), or use XSLT to do the conversion. 如果您关心这一点,您可以查看其他XML解析器(如CrackCobraVsMongoose ),或使用XSLT进行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM