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

时间:2022-02-28 21:50:22

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?

以前有人遇到过这种情况吗?

7 个解决方案

#1


81  

I think this is the best one: Converting between XML and JSON

我认为这是最好的方法:在XML和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. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit.

请务必阅读xml.com O'Reilly站点上附带的文章,该文章详细介绍了这些转换的问题,我认为您会发现这些问题具有启发性。奥莱利主持这篇文章的事实表明,Stefan的解决方案是有价值的。

#2


39  

https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/):

我自己的库(更新URL http://code.google.com/p/x2js/):

This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries.

这个库提供XML到JSON (JavaScript对象),反之亦然。这个库非常小,不需要任何其他的库。

API functions

API函数

  • new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here
  • 新的X2JS()——创建实例以访问所有库功能。还可以在这里指定可选的配置选项。
  • 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);

#3


15  

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.

内容是我存储xml的字段。

#4


2  

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. Features :- Parse xml to json object. Print json object back to xml. Can be used to save xml in IndexedDB as X2J objects. Print json object.

Synopsys:一个不仅可以将xml转换为json的库,而且还很容易调试(没有循环错误),并将json重新创建回xml的库。特性:-解析xml到json对象。将json对象打印回xml。可以将xml保存在IndexedDB中作为X2J对象。打印json对象。

#5


2  

I would personally recommend this tool. It is an XML to JSON converter.

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

It is very lightweight and is in pure JavaScript. It needs no dependencies. You can simply add the functions to your code and use it as you wish.

它是非常轻量级的,并且使用纯JavaScript。它不需要依赖。您可以简单地将函数添加到代码中,并按自己的意愿使用它。

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!

这是一个在线演示!

#6


0  

Disclaimer: I've written fast-xml-parser

免责声明:我写fast-xml-parser

Fast XML Parser can help to convert XML to JSON and vice versa. Here is the example;

快速XML解析器可以帮助将XML转换为JSON,反之亦然。这是例子;

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);

#7


-1  

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. Ultimately I ended up doing it server side using Newtonsoft in ASP.MVC. Here is the online converter http://techfunda.com/Tools/XmlToJson

使用服务器端作为客户端的最佳方式在所有场景中都不能正常工作。我试图使用javascript构建在线json到xml和xml到json转换器,我觉得几乎不可能,因为它不是在所有的场景中工作的。最终,我在asp.net mvc中使用Newtonsoft完成了it服务器端。这里是在线转换器http://techfunda.com/Tools/XmlToJson

#1


81  

I think this is the best one: Converting between XML and JSON

我认为这是最好的方法:在XML和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. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit.

请务必阅读xml.com O'Reilly站点上附带的文章,该文章详细介绍了这些转换的问题,我认为您会发现这些问题具有启发性。奥莱利主持这篇文章的事实表明,Stefan的解决方案是有价值的。

#2


39  

https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/):

我自己的库(更新URL http://code.google.com/p/x2js/):

This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries.

这个库提供XML到JSON (JavaScript对象),反之亦然。这个库非常小,不需要任何其他的库。

API functions

API函数

  • new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here
  • 新的X2JS()——创建实例以访问所有库功能。还可以在这里指定可选的配置选项。
  • 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);

#3


15  

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.

内容是我存储xml的字段。

#4


2  

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. Features :- Parse xml to json object. Print json object back to xml. Can be used to save xml in IndexedDB as X2J objects. Print json object.

Synopsys:一个不仅可以将xml转换为json的库,而且还很容易调试(没有循环错误),并将json重新创建回xml的库。特性:-解析xml到json对象。将json对象打印回xml。可以将xml保存在IndexedDB中作为X2J对象。打印json对象。

#5


2  

I would personally recommend this tool. It is an XML to JSON converter.

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

It is very lightweight and is in pure JavaScript. It needs no dependencies. You can simply add the functions to your code and use it as you wish.

它是非常轻量级的,并且使用纯JavaScript。它不需要依赖。您可以简单地将函数添加到代码中,并按自己的意愿使用它。

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!

这是一个在线演示!

#6


0  

Disclaimer: I've written fast-xml-parser

免责声明:我写fast-xml-parser

Fast XML Parser can help to convert XML to JSON and vice versa. Here is the example;

快速XML解析器可以帮助将XML转换为JSON,反之亦然。这是例子;

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);

#7


-1  

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. Ultimately I ended up doing it server side using Newtonsoft in ASP.MVC. Here is the online converter http://techfunda.com/Tools/XmlToJson

使用服务器端作为客户端的最佳方式在所有场景中都不能正常工作。我试图使用javascript构建在线json到xml和xml到json转换器,我觉得几乎不可能,因为它不是在所有的场景中工作的。最终,我在asp.net mvc中使用Newtonsoft完成了it服务器端。这里是在线转换器http://techfunda.com/Tools/XmlToJson