IT박스

Javascript를 사용하여 XML을 JSON으로 변환

itboxs 2020. 6. 25. 22:03
반응형

Javascript를 사용하여 XML을 JSON으로 변환


XML에서 JSON으로 변환 한 다음 다시 XML로 어떻게 변환 하시겠습니까?

다음 도구는 잘 작동하지만 완전히 일치하지는 않습니다.

전에이 상황에 처한 사람이 있습니까?


이것이 가장 좋은 방법이라고 생각합니다 .XML과 JSON 간 변환

xml.com O'Reilly 사이트 에서 동봉 된 기사 를 읽으십시오 . 여기에서 이러한 변환 관련 문제에 대한 자세한 내용을 살펴볼 수 있습니다. O'Reilly가 기사를 호스팅하고 있다는 사실은 Stefan의 솔루션에 장점이 있음을 나타냅니다.


https://github.com/abdmob/x2js- 내 라이브러리 ( http://code.google.com/p/x2js/ 에서 업데이트 된 URL ) :

이 라이브러리는 XML에서 JSON (JavaScript Objects)으로 또는 그 반대로 Javascript 변환 함수를 제공합니다. 라이브러리는 매우 작으며 다른 추가 라이브러리가 필요하지 않습니다.

API 함수

  • 새로운 X2JS ()-인스턴스를 생성하여 모든 라이브러리 기능에 액세스합니다. 또한 여기에서 선택적 구성 옵션을 지정할 수 있습니다
  • X2JS.xml2json-DOM 오브젝트로 지정된 XML을 JSON으로 변환
  • X2JS.json2xml-JSON을 XML DOM 오브젝트로 변환
  • X2JS.xml_str2json-문자열로 지정된 XML을 JSON으로 변환
  • X2JS.json2xml_str-JSON을 XML 문자열로 변환

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

이 답변은이 기능을 수행하는 데 많은 도움이되었습니다.

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

jquery dom / xml 객체를 전달하는 한 다음과 같습니다.

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

여기서 내용은 내가 내 XML을 저장 한 분야이다.


A while back I wrote this tool https://bitbucket.org/surenrao/xml2json for my TV Watchlist app, hope this helps too.

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.


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

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.

It also takes the XML attributes into considerations.

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 can help to convert XML to JSON and vice versa. 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

//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.

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.
I found doing the following is much easier (if the xml only occurs once..)

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


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

참고URL : https://stackoverflow.com/questions/1773550/convert-xml-to-json-and-back-using-javascript

반응형