将 XML 转换为 JavaScript 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13600219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert XML to JavaScript Object
提问by moey
I have an XML file with the following content:
我有一个包含以下内容的 XML 文件:
<directory>
<app>
<title>Carrot</title>
<url>www.carrot.com</url>
</app>
<app>
<title>Cucumber</title>
<url>www.cucumber.com</url>
</app>
</directory>
Assuming I had been able to read it and store the content as a string:
假设我已经能够读取它并将内容存储为字符串:
s = '<directory><app><title>Carrot</title><url>www.google.com</url></app><app><title>Cucumber</title><url>www.cucumber.com</url></app></directory>';
How do I convert it to a JavaScript object like the following?
如何将其转换为如下所示的 JavaScript 对象?
{
"directory": {
"app": [
{ "title": "Carrot", "url": "www.carrot.com" },
{ "title": "Cucumber", "url": "www.cucumber.com" }
]
}
}
回答by Blowsie
I use this plugin ... http://www.thomasfrank.se/xml_to_json.html
我使用这个插件... http://www.thomasfrank.se/xml_to_json.html
Its always worked a charm for me.
它对我来说总是很有魅力。
回答by Christian Westman
I think you are looking for the answer to the following question Convert XML to JSON (and back) using Javascript
我认为您正在寻找以下问题的答案使用 Javascript 将 XML 转换为 JSON(并返回)
XML <-> JSON conversion in Javascript
Javascript 中的 XML <-> JSON 转换
quoted answer
引用答案
I think this is the best one: Converting between XML and JSON
Be sure to read the accompanying article on the Xml.com O'Reilly site (linked to at the >bottom). The writer goes into details of the problems with these conversions, which I think >you will find enlightening. The fact that O'Reilly is hosting the article should indicate >that Stefan's solution has merit.
我认为这是最好的:Converting between XML and JSON
请务必阅读 Xml.com O'Reilly 站点上随附的文章(链接到 > 底部)。作者详细介绍了这些转换的问题,我认为 > 你会发现它很有启发性。O'Reilly 主持这篇文章的事实应该表明 > Stefan 的解决方案是有价值的。