简体   繁体   English

使用 Javascript 将 XML 转换为 JSON(并返回)

[英]Convert XML to JSON (and back) using Javascript

How would you convert from XML to JSON and then back to XML?你如何将 XML 转换为 JSON,然后再转换回 XML?

The following tools work quite well, but aren't completely consistent:以下工具工作得很好,但并不完全一致:

Has anyone encountered this situation before?有没有人遇到过这种情况?

I think this is the best one: Converting between XML and JSON我认为这是最好的: Converting between XML and JSON

Be sure to read the accompanying article on the xml.com O'Reilly site , which goes into details of the problems with these conversions, which I think you will find enlightening.请务必阅读xml.com O'Reilly 站点上随附的文章,其中详细介绍了这些转换的问题,我想您会从中发现启发。 The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit. O'Reilly 主持这篇文章的事实应该表明 Stefan 的解决方案是有价值的。

https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/ ): https://github.com/abdmob/x2js - 我自己的库(来自http://code.google.com/p/x2js/ 的更新 URL):

This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions.该库提供 XML 到 JSON(JavaScript 对象),反之亦然 javascript 转换功能。 The library is very small and doesn't require any other additional libraries.该库非常小,不需要任何其他额外的库。

API functions API函数

  • new X2JS() - to create your instance to access all library functionality. new X2JS() - 创建您的实例以访问所有库功能。 Also you could specify optional configuration options here您也可以在此处指定可选配置选项
  • X2JS.xml2json - Convert XML specified as DOM Object to JSON X2JS.xml2json - 将指定为 DOM 对象的 XML 转换为 JSON
  • X2JS.json2xml - Convert JSON to XML DOM Object X2JS.json2xml - 将 JSON 转换为 XML DOM 对象
  • X2JS.xml_str2json - Convert XML specified as string to JSON X2JS.xml_str2json - 将指定为字符串的 XML 转换为 JSON
  • X2JS.json2xml_str - Convert JSON to XML string X2JS.json2xml_str - 将 JSON 转换为 XML 字符串

Online Demo on http://jsfiddle.net/abdmob/gkxucxrj/1/ http://jsfiddle.net/abdmob/gkxucxrj/1/ 上的在线演示

var x2js = new X2JS();
function convertXml2JSon() {
    $("#jsonArea").val(JSON.stringify(x2js.xml_str2json($("#xmlArea").val())));
}

function convertJSon2XML() {
    $("#xmlArea").val(x2js.json2xml_str($.parseJSON($("#jsonArea").val())));
}

convertXml2JSon();
convertJSon2XML();
$("#convertToJsonBtn").click(convertXml2JSon);
$("#convertToXmlBtn").click(convertJSon2XML);

These answers helped me a lot to make this function:这些答案对我完成此功能有很大帮助:

function xml2json(xml) {
  try {
    var obj = {};
    if (xml.children.length > 0) {
      for (var i = 0; i < xml.children.length; i++) {
        var item = xml.children.item(i);
        var nodeName = item.nodeName;

        if (typeof (obj[nodeName]) == "undefined") {
          obj[nodeName] = xml2json(item);
        } else {
          if (typeof (obj[nodeName].push) == "undefined") {
            var old = obj[nodeName];

            obj[nodeName] = [];
            obj[nodeName].push(old);
          }
          obj[nodeName].push(xml2json(item));
        }
      }
    } else {
      obj = xml.textContent;
    }
    return obj;
  } catch (e) {
      console.log(e.message);
  }
}

As long as you pass in a jquery dom/xml object: for me it was:只要你传入一个 jquery dom/xml 对象:对我来说它是:

Jquery(this).find('content').eq(0)[0]

where content was the field I was storing my xml in.其中content是我存储 xml 的字段。

A while back I wrote this tool https://bitbucket.org/surenrao/xml2json for my TV Watchlist app, hope this helps too.不久前,我为我的 TV Watchlist 应用编写了这个工具https://bitbucket.org/surenrao/xml2json ,希望这也能有所帮助。

Synopsys: A library to not only convert xml to json, but is also easy to debug (without circular errors) and recreate json back to xml. Synopsys:一个库,不仅可以将 xml 转换为 json,而且还易于调试(没有循环错误)并将 json 重新创建回 xml。 Features :- Parse xml to json object.特点:- 将 xml 解析为 json 对象。 Print json object back to xml.将 json 对象打印回 xml。 Can be used to save xml in IndexedDB as X2J objects.可用于将 IndexedDB 中的 xml 保存为 X2J 对象。 Print json object.打印 json 对象。

I've created a recursive function based on regex, in case you don't want to install library and understand the logic behind what's happening:我已经创建了一个基于正则表达式的递归函数,以防您不想安装库并了解发生的事情背后的逻辑:

 const xmlSample = '<tag>tag content</tag><tag2>another content</tag2><tag3><insideTag>inside content</insideTag><emptyTag /></tag3>'; console.log(parseXmlToJson(xmlSample)); function parseXmlToJson(xml) { const json = {}; for (const res of xml.matchAll(/(?:<(\\w*)(?:\\s[^>]*)*>)((?:(?!<\\1).)*)(?:<\\/\\1>)|<(\\w*)(?:\\s*)*\\/>/gm)) { const key = res[1] || res[3]; const value = res[2] && parseXmlToJson(res[2]); json[key] = ((value && Object.keys(value).length) ? value : res[2]) || null; } return json; }

Regex explanation for each loop:每个循环的正则表达式解释:

  • res[0] - return the xml (as is) res[0] - 返回 xml(原样)
  • res[1] - return the xml tag name res[1] - 返回 xml 标签名称
  • res[2] - return the xml content res[2] - 返回 xml 内容
  • res[3] - return the xml tag name in case the tag closes itself. res[3] - 返回 xml 标签名称,以防标签自行关闭。 In example: <tag />例如: <tag />

You can check how the regex works here: https://regex101.com/r/ZJpCAL/1您可以在此处查看正则表达式的工作原理: https : //regex101.com/r/ZJpCAL/1

Note: In case json has a key with an undefined value, it is being removed.注意:如果 json 有一个未定义值的键,它将被删除。 That's why I've inserted null at the end of line 9.这就是我在第 9 行末尾插入 null 的原因。

You can also use txml .您也可以使用txml It can parse into a DOM made of simple objects and stringify.它可以解析为由简单对象和字符串化组成的 DOM。 In the result, the content will be trimmed.结果,内容将被修剪。 So formating of the original with whitespaces will be lost.所以用空格格式化原件将丢失。 But this could be used very good to minify HTML.但这可以很好地用于缩小 HTML。

const xml = require('txml');
const data = `
<tag>tag content</tag>
<tag2>another content</tag2>
<tag3>
  <insideTag>inside content</insideTag>
  <emptyTag />
</tag3>`;

const dom = xml(data); // the dom can be JSON.stringified

xml.stringify(dom); // this will return the dom into an xml-string

Disclaimer: I am the author of txml , the fastest xml parser in javascript.免责声明:我是txml的作者,这是 javascript 中最快的 xml 解析器。

I would personally recommend this tool .我个人会推荐这个工具 It is an XML to JSON converter.它是一个 XML 到 JSON 的转换器。

It is very lightweight and is in pure JavaScript.它非常轻量级并且使用纯 JavaScript。 It needs no dependencies.它不需要依赖项。 You can simply add the functions to your code and use it as you wish.您可以简单地将这些函数添加到您的代码中,并根据需要使用它。

It also takes the XML attributes into considerations.它还考虑了 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”}}’

Here's an online demo !这是一个在线演示

Disclaimer: I've written fast-xml-parser免责声明:我已经编写了fast-xml-parser

Fast XML Parser can help to convert XML to JSON and vice versa. Fast XML Parser 可以帮助将 XML 转换为 JSON,反之亦然。 Here is the example;这是示例;

var options = {
    attributeNamePrefix : "@_",
    attrNodeName: "attr", //default is 'false'
    textNodeName : "#text",
    ignoreAttributes : true,
    ignoreNameSpace : false,
    allowBooleanAttributes : false,
    parseNodeValue : true,
    parseAttributeValue : false,
    trimValues: true,
    decodeHTMLchar: false,
    cdataTagName: "__cdata", //default is 'false'
    cdataPositionChar: "\\c",
};
if(parser.validate(xmlData)=== true){//optional
    var jsonObj = parser.parse(xmlData,options);
}

If you want to parse JSON or JS object into XML then如果要将 JSON 或 JS 对象解析为 XML,则

//default options need not to set
var defaultOptions = {
    attributeNamePrefix : "@_",
    attrNodeName: "@", //default is false
    textNodeName : "#text",
    ignoreAttributes : true,
    encodeHTMLchar: false,
    cdataTagName: "__cdata", //default is false
    cdataPositionChar: "\\c",
    format: false, 
    indentBy: "  ",
    supressEmptyNode: false
};
var parser = new parser.j2xParser(defaultOptions);
var xml = parser.parse(json_or_js_obj);

Here ' a good tool from a documented and very famous npm library that does the xml <-> js conversions very well: differently from some (maybe all) of the above proposed solutions, it converts xml comments also.是一个来自有记录且非常著名的 npm 库的一个很好的工具,它可以很好地进行 xml <-> js 转换:与上面提出的一些(也许全部)解决方案不同,它也转换 xml 注释。

var obj = {name: "Super", Surname: "Man", age: 23};

var builder = new xml2js.Builder();
var xml = builder.buildObject(obj);

I was using xmlToJson just to get a single value of the xml.我使用 xmlToJson 只是为了获取 xml 的单个值。
I found doing the following is much easier (if the xml only occurs once..)我发现执行以下操作要容易得多(如果 xml 只出现一次..)

 let xml = '<person>' + ' <id>762384324</id>' + ' <firstname>Hank</firstname> ' + ' <lastname>Stone</lastname>' + '</person>'; let getXmlValue = function(str, key) { return str.substring( str.lastIndexOf('<' + key + '>') + ('<' + key + '>').length, str.lastIndexOf('</' + key + '>') ); } alert(getXmlValue(xml, 'firstname')); // gives back Hank

There is an open sourced library Xml-to-json with methods jsonToXml(json) and xmlToJson(xml).有一个开源库Xml-to-json ,方法是 jsonToXml(json) 和 xmlToJson(xml)。

Here's an online demo !这是一个在线演示

In 6 simple ES6 lines:在 6 条简单的 ES6 行中:

xml2json = xml => {                                                                                                                                                     
  var el = xml.nodeType === 9 ? xml.documentElement : xml                                                                                                               
  var h  = {name: el.nodeName}                                                                                                                                          
  h.content    = Array.from(el.childNodes || []).filter(e => e.nodeType === 3).map(e => e.textContent).join('').trim()                                                  
  h.attributes = Array.from(el.attributes || []).filter(a => a).reduce((h, a) => { h[a.name] = a.value; return h }, {})                                                 
  h.children   = Array.from(el.childNodes || []).filter(e => e.nodeType === 1).map(c => h[c.nodeName] = xml2json(c))                                                    
  return h                                                                                                                                                              
}  

Test with echo "xml2json_example()" | node -r xml2json.es6使用echo "xml2json_example()" | node -r xml2json.es6 echo "xml2json_example()" | node -r xml2json.es6 with source at https://github.com/brauliobo/biochemical-db/blob/master/lib/xml2json.es6 echo "xml2json_example()" | node -r xml2json.es6源在https://github.com/brauliobo/biochemical-db/blob/master/lib/xml2json.es6

Xml-to-json library has methods jsonToXml(json) and xmlToJson(xml) . Xml-to-json库有方法jsonToXml(json)xmlToJson(xml)

Here's an online demo !这是一个在线演示

The best way to do it using server side as client side doesn't work well in all scenarios.使用服务器端作为客户端的最佳方法并不适用于所有场景。 I was trying to build online json to xml and xml to json converter using javascript and I felt almost impossible as it was not working in all scenarios.我试图使用 javascript 构建在线 json 到 xml 和 xml 到 json 转换器,我觉​​得几乎不可能,因为它不能在所有场景中工作。 Ultimately I ended up doing it server side using Newtonsoft in ASP.MVC.最终,我最终在 ASP.MVC 中使用 Newtonsoft 完成了服务器端。 Here is the online converter http://techfunda.com/Tools/XmlToJson这是在线转换器http://techfunda.com/Tools/XmlToJson

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

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