XML 字符串到 JSON javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36929478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:43:59  来源:igfitidea点击:

XML string to JSON javascript

javascriptjson

提问by Abhinav Parashar

I have a xml string which i want to convert in JSON string

我有一个 xml 字符串,我想将其转换为 JSON 字符串

var txt = "<?xml version='1.0' encoding='UTF-8' ?>
                 <result>
                   <info>
                      <id>1</id>
                      <type>HL</type>
                      <ven>DEMOMA</ven>
                   </info>
                   <info>
                      <id>2</id>
                      <type>HL</type>
                      <ven>DEMOMB</ven>
                   </info>
               <result>";

i tried to initially convert it in DOM object using parser but it throws parsing error.

我最初尝试使用解析器将其转换为 DOM 对象,但它引发了解析错误。

parser = new DOMParser();
xmlDoc = parser.parseFromString(txt,"text/xml");

i want my output json string like only by using Javascript

我希望我的输出 json 字符串就像只使用 Javascript

{"result":[{"id":"1","type":"HL","ven":"DEMOMA"},{"id":"2","type":"HL","ven":"DEMOMB"}]}

回答by Mikhail

I will try to explain with an example with use x2js.jshttps://github.com/abdmob/x2jsand jquery(and without jQuery) library.

我将尝试用一个例子来解释使用x2js.jshttps://github.com/abdmob/x2jsjquery(没有 jQuery)库。

GET XML data from the API and convert this data to JSON

从 API 获取 XML 数据并将此数据转换为 JSON

With jQuery

使用 jQuery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
    <script type="text/javascript" src="xml2json.js"></script>
</head>
<body>
    <script type="text/javascript">
    var x2js = new X2JS();
    $.ajax({
        url: 'http://ip-api.com/xml',
        dataType: 'XML',
        success: function(data) {
            var xmlText = data; // XML
            var jsonObj = x2js.xml2json(xmlText); // Convert XML to JSON
            console.log(jsonObj);
        }
    });
    </script>
</body>
</html>

without jQuery

没有 jQuery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="xml2json.js"></script>
</head>
<body>
    <script type="text/javascript">
    function loadXMLDoc(dname) {
        if (window.XMLHttpRequest) {
            xhttp = new XMLHttpRequest();
        } else {
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhttp.open("GET", dname, false);
        xhttp.send();
        return xhttp.responseXML;
    }

    var xmlDoc = loadXMLDoc("http://ip-api.com/xml"); // XML
    var x2js = new X2JS();
    var jsonObj = x2js.xml2json(xmlDoc); // Convert XML to JSON
    console.log(jsonObj);
    </script>
</body>
</html>

and using the example that you gave in question. Fix closed <result>to </result>

并使用您提供的示例。修复关闭<result></result>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="xml2json.js"></script>
</head>
<body>
    <script type="text/javascript">
        var txt = "<?xml version='1.0' encoding='UTF-8' ?> <result> <info> <id>1</id> <type>HL</type> <ven>DEMOMA</ven> </info> <info> <id>2</id> <type>HL</type> <ven>DEMOMB</ven> </info> </result>";
        var x2js = new X2JS();
        var jsonObj = x2js.xml_str2json(txt);
        console.log(jsonObj);
    </script>
</body>
</html>

回答by pramjeet

Check out this https://github.com/metatribal/xmlToJSON

看看这个https://github.com/metatribal/xmlToJSON

Its a very small and useful script. Usage is very easy.

它是一个非常小而有用的脚本。使用非常简单。

Include the src

包括 src

<script type="text/javascript" src="path/xmlToJSON.js"></script>

<script type="text/javascript" src="path/xmlToJSON.js"></script>

and enjoy! xmlToJSON is packaged as a simple module, so use it like this

享受!xmlToJSON 被打包成一个简单的模块,所以像这样使用它

testString = '<xml><a>It Works!</a></xml>';   // get some xml (string or document/node)
result = xmlToJSON.parseString(testString);   // parse

'result' is your JSON object.

'result' 是您的 JSON 对象。

回答by Valentyn Kolesnikov

Check out this https://github.com/javadev/xml-to-jsonLive example

查看这个https://github.com/javadev/xml-to-json现场示例

I am the maintainer of the library.

我是图书馆的维护者。

<script type="text/javascript" src="path/xmltojson.js"></script>

var json = xmlToJson(`<?xml version="1.0" encoding="UTF-8" ?>
             <result>
               <info>
                  <id>1</id>
                  <type>HL</type>
                  <ven>DEMOMA</ven>
               </info>
               <info>
                  <id>2</id>
                  <type>HL</type>
                  <ven>DEMOMB</ven>
               </info>
           </result>`);

// {
//   "result": {
//     "info": [
//       {
//         "id": "1",
//         "type": "HL",
//         "ven": "DEMOMA"
//       },
//       {
//         "id": "2",
//         "type": "HL",
//         "ven": "DEMOMB"
//       }
//     ]
//   }
// }

var xml = jsonToXml("{}");

// <?xml version="1.0" encoding="UTF-8"?>
// <root></root>