Core points
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; }
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);
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; } }
So, if example.xml returns the following XML data:
<?xml version="1.0"?><statuses><status><id>1</id><text>Hello!</text></status></statuses>
XML2jsobj(xhr.responseXML.documentElement) will return the following object:
{ status: { id: ["one", 1], text: "Hello!" } }
Therefore, you can use obj.status.text to retrieve the "Hello!" text.
Precautions
Some notes about XML2jsobj:
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!