将XML转换为JavaScript对象

4

我有一个包含以下内容的XML文件:

<directory>
  <app>
    <title>Carrot</title>
    <url>www.carrot.com</url>
  </app>
  <app>
    <title>Cucumber</title>
    <url>www.cucumber.com</url>
  </app>
</directory>

假设我已能够将其读取并存储为字符串:

s = '<directory><app><title>Carrot</title><url>www.google.com</url></app><app><title>Cucumber</title><url>www.cucumber.com</url></app></directory>';

如何将它转换为以下格式的 JavaScript 对象?
{
  "directory": {
    "app": [
      { "title": "Carrot", "url": "www.carrot.com" },
      { "title": "Cucumber", "url": "www.cucumber.com" }
    ]  
  }
}

我认为你正在寻找以下问题的答案:https://dev59.com/P3I-5IYBdhLWcg3wm5lG - Christian Westman
你是想直接将它转换成Javascript对象,还是只需要一个JSON字符串? - nullability
2个回答

3

2

我认为您正在寻找以下问题的答案:使用Javascript将XML转换为JSON(反之亦然)

Javascript中的XML <-> JSON转换

引用的答案

我认为这是最好的解决方案:在XML和JSON之间进行转换

一定要阅读Xml.com O'Reilly网站上的附带文章(链接在底部)。作者详细介绍了这些转换存在的问题,我认为您会发现这很有启发性。O'Reilly托管该文章表明Stefan的解决方案具有价值。


请务必阅读底部链接的Xml.com O'Reilly网站上的附带文章。 - Anmol Saraf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接