使用Javascript将XML转换为JSON(并且反向转换)

176

如何将XML转换为JSON,再将其转换回XML?

以下工具效果很好,但不完全一致:

有人遇到过这种情况吗?


12
请解释这些不一致之处。 - Josh Stodola
4
具体而言,涉及将只有1个元素的JSON数组转换为XML。当您将其转换回JSON时,它不会创建一个1元素数组,而是创建了一个对象字面量。我通过使用$.isArray()来检查类型,并在! $.isArray()情况下将其包装在数组中来解决这个问题。 - Jason Suárez
1
xml2json - http://www.fyneworks.com/jquery/xml-to-json/ - 在2013年2月15日14:25 AEST之后出现了500错误。 - ysrb
json2xml的链接已经失效。 - whirlwin
你尝试过这个吗?https://devtoolsonline20190908040816.azurewebsites.net/DevTools/Convert_JSON2XML - GomuGomuNoRocket
显示剩余2条评论
14个回答

0

我个人推荐这个工具。它是一个XML转JSON的转换器。

它非常轻量级,使用纯JavaScript编写,不需要任何依赖。您可以将其函数添加到您的代码中,并根据您的需求使用它。

它还考虑了XML属性。

var xml = ‘<person id=”1234” age=”30”><name>John Doe</name></person>’;
var json = xml2json(xml); 

console.log(json); 
// prints ‘{“person”: {“id”: “1234”, “age”: “30”, “name”: “John Doe”}}’

这里有一个在线演示


10
Github仓库未找到。 - brauliobo

0

有一个开源库Xml-to-json,其中包含方法jsonToXml(json)和xmlToJson(xml)。

这里有一个在线演示


0

该函数直接读取XMLDocument(或文档节点/元素)的DOM属性,以完全准确地构建JSON,而不是尝试猜测或匹配。请传递XMLHttpRequest中的responseXML,而不是responseText

xml2json(xmlDoc)

如果你只有一串XML字符串,而不是一个XMLDocument,jQuery会将你的文本转换为一个。

xml2json($(xmlString)[0])
  • 每个节点都成为一个对象。(所有元素都是节点,但不是所有节点都是元素(例如元素内的文本)。)
  • 每个对象都包含节点名称和类型。
  • 如果它有属性,则它们会出现在attributes对象中作为属性。
  • 如果它有子节点,则它们会递归地出现为节点->对象在children数组中。
  • 如果它是文本、CDATA或注释节点(元素标记之间的裸文本)或注释,则不应该有attributeschildren,但文本将在text属性中。
{
  // Always present
  "name": "FancyElement",
  "type": "Element",

  // If present
  "attributes: {
    "attr1": "val1",
    "attr2": "val2"
  },
  "children": [...],
  "text": "buncha fancy words"
}

注意:我不熟悉所有节点类型。它可能无法从所有节点中获取所需/有用的信息。它已在以下节点上进行了测试并表现如预期:
- 元素 - 文本 - CDATA - 注释 - 文档

function xml2json(xml) {
  try {
    const types = [null,
      "Element",
      "Attribute",
      "Text",
      "CDATA",
      "EntityReference", // Deprecated
      "Entity", // Deprecated
      "ProcessingInstruction",
      "Comment",
      "Document",
      "DocumentType",
      "DocumentFragment",
      "Notation" // Deprecated
    ];

    var o = {};
    o.name = xml.nodeName;
    o.type = types[xml.nodeType];

    if (xml.nodeType == 3 ||
        xml.nodeType == 4 ||
        xml.nodeType == 8 ) {
      o.text = xml.textContent;
    } else {
      if (xml.attributes) {
        o.attributes = {};
        for (const a of xml.attributes) {
          o.attributes[a.name] = a.value;
        }
      }

      if (xml.childNodes.length) {
        o.children = [];
        for (const x of xml.childNodes) {
          o.children.push(xml2json(x))
        }
      }
    }
    return (o);
  } catch (e) {
    alert('Error in xml2json. See console for details.');
    console.log('Error in xml2json processing node:');
    console.log(o);
    console.log('Error:');
    console.log(e);
  }
}

var doc = document.getElementById("doc");
var out = document.getElementById("out");

out.innerText = JSON.stringify(xml2json(doc), null, 2);
/* Let's process the whole Code Snippet #document, why not?
 * Yes, the JSON we just put in the document body and all 
 * this code is encoded in the JSON in the console.
 * In that copy you can see why the XML DOM will all be one line.
 * The JSON in the console has "\n" nodes all throughout.
 */
console.log(xml2json(document));
#doc,
#out {
  border: 1px solid black;
}
<div id="doc"><!-- The XML DOM will all be on one line --><div personality="bubbly" relevance=42>This text is valid for HTML.<span>But it probably shouldn't be siblings to an element in XML.</span></div></div>

<pre id="out"></pre>


-5

最好的方法是使用服务器端,因为客户端不适用于所有场景。我试图使用 JavaScript 构建在线 json 到 xml 和 xml 到 json 转换器,但几乎无法在所有情况下正常工作。最终我使用 ASP.MVC 中的 Newtonsoft 在服务器端进行了转换。这是在线转换器 http://techfunda.com/Tools/XmlToJson


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