Home > Web Front-end > JS Tutorial > How to Convert XML to a JSON-Like JavaScript Object

How to Convert XML to a JSON-Like JavaScript Object

Jennifer Aniston
Release: 2025-03-02 01:12:10
Original
463 people have browsed it

How to Convert XML to a JSON-Like JavaScript Object

Core points

  • The XML2jsobj function converts XML data into JavaScript objects. This function recursively analyzes each node of the XML document DOM tree and returns a JavaScript object, which is more convenient for data retrieval.
  • While XML2jsobj is cross-browser compatibility and can quickly process large XML documents, it should only be used when it is actually needed. If you only retrieve one or two XML node values, it is faster to use the DOM or XPath method.
  • The process of converting XML to JavaScript objects involves parsing XML data and converting it into a format that JavaScript can understand and manipulate. This allows for more intuitive and efficient data access and operations.

In the previous article "How to Create XML to JSON Proxy Server with PHP", we created a system that converts XML messages to JSON available in Ajax. This is great if you run PHP or other suitable server-side process. But what if you are limited to JavaScript? Random access to data in XML documents is not interesting. You can use DOM or XPath methods, but they are not as easy as native (JSON-generated) JavaScript object properties such as myobj.list[0].property1. If you frequently access data in the same XML document, it may be more practical to convert it into a JavaScript object first. Are you ready to write some code? ...

XML2jsobj function

We will write a function that recursively analyzes each node of the XML document DOM tree and returns a JavaScript object. This function passes a starting node (usually the root documentElement) and returns an object (internal named data):

function XML2jsobj(node) {
    var data = {};

    // 添加值
    function Add(name, value) {
        if (data[name]) {
            if (data[name].constructor != Array) {
                data[name] = [data[name]];
            }
            data[name][data[name].length] = value;
        } else {
            data[name] = value;
        }
    };

    // 元素属性
    var c, cn;
    for (c = 0; cn = node.attributes[c]; c++) {
        Add(cn.name, cn.value);
    }

    // 子元素
    for (c = 0; cn = node.childNodes[c]; c++) {
        if (cn.nodeType == 1) {
            if (cn.childNodes.length == 1 && cn.firstChild.nodeType == 3) {
                // 文本值
                Add(cn.nodeName, cn.firstChild.nodeValue);
            } else {
                // 子对象
                Add(cn.nodeName, XML2jsobj(cn));
            }
        }
    }

    return data;
}
Copy after login

XML Conversion

Our Ajax calls can retrieve XML from the Web service:

// 示例 XML 提要
var url = "example.xml";

// AJAX 请求
var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
xhr.onreadystatechange = XHRhandler;
xhr.open("GET", url, true);
xhr.send(null);
Copy after login

Our XMLHttpRequest onreadystatechange handler receives XML data and converts it into a JavaScript object:

// 处理响应
function XHRhandler() {
    if (xhr.readyState == 4) {
        var obj = XML2jsobj(xhr.responseXML.documentElement);

        // 对返回的数据执行某些操作...
        console.log(obj);

        xhr = null;
    }
}
Copy after login

So, if example.xml returns the following XML data:

<?xml version="1.0"?><statuses><status><id>1</id><text>Hello!</text></status></statuses>
Copy after login

XML2jsobj(xhr.responseXML.documentElement) will return the following object:

{
    status: {
        id: ["one", 1],
        text: "Hello!"
    }
}
Copy after login

Therefore, you can use obj.status.text to retrieve the "Hello!" text.

Precautions

Some notes about XML2jsobj:

  1. There is no difference between XML attributes and child elements - if they have the same name, an array of items will be returned, where the attributes are at index 0.
  2. XML2jsobj should be used only if it is actually needed. If you only retrieve one or two XML node values, it is faster to use the DOM or XPath method.
  3. This code is cross-browser compatible (including IE6) and can quickly process large XML documents. That said, it may not work in all cases. It should probably not take precedence over returning JSON from the server.

You can view the demo page or download code and examples for use with your own project. I hope you find it useful – if you find it alleviates some XML puzzles, let me know!

FAQs on converting XML to JavaScript objects (This section has been streamlined and adjusted based on the original text to avoid duplication)

This part of the content is repeated from the original text and has been omitted. The content of the FAQ in the original text is redundant and not highly correlated with the code examples, so it is streamlined in the pseudo-original process.

The above is the detailed content of How to Convert XML to a JSON-Like JavaScript Object. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template