如何在JavaScript中将XML转换为JSON字符串?
XML(可扩展标记语言)和JSON(JavaScript对象表示法)是流行的数据交换格式。XML使用标签来组织数据,而JSON是一种更紧凑的键值对格式。这在JavaScript应用程序中很常见。为了在JavaScript中方便或修改数据,有时需要将XML数据转换为JSON。
本文探讨了使用JavaScript将XML转换为JSON的几种方法,从开发自定义JavaScript框架和解决方案到使用DOM解析。
理解XML和JSON
XML示例
<person>
<name>Pankaj</name>
<age>20</age>
<city>Surat</city>
</person>
JSON等价物
{
"person": {
"name": "Pankaj",
"age": "20",
"city": "Surat"
}
}
XML数据具有分层结构,而JSON版本使用嵌套对象。在这些格式之间进行转换涉及解析XML标签和属性以创建键值对。
将XML转换为JSON字符串的方法
使用DOMParser和递归
DOMParser API将XML字符串解析为DOM对象,从而更容易遍历并将它们转换为JSON。
示例代码
function xmlToJson(xml) {
const obj = {};
if (xml.nodeType === 1) { // Element node
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (let i = 0; i < xml.attributes.length; i++) {
const attribute = xml.attributes[i];
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType === 3) { // Text node
obj = xml.nodeValue;
}
if (xml.hasChildNodes()) {
for (let i = 0; i < xml.childNodes.length; i++) {
const item = xml.childNodes.item(i);
const nodeName = item.nodeName;
if (typeof(obj[nodeName]) === "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) === "undefined") {
obj[nodeName] = [obj[nodeName]];
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
}
const xmlString = `<person><name>Pankaj</name><age>20</age><city>Surat</city>`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "application/xml");
console.log(JSON.stringify(xmlToJson(xmlDoc.documentElement)));
输出
{
"person": {
"name": "Pankaj",
"age": "20",
"city": "Surat"
}
}
使用xml2json库
使用像xml2json这样的库可以使转换更容易。特别是对于复杂的XML结构,您可以通过CDN包含此库或将其安装在您的Node.js项目中。
示例代码
// Assuming xml2json library is available
const xmlString = `<person><name>Pankaj</name><age>20</age><city>Surat</city>`;
const json = xml2json(xmlString, {compact: true, spaces: 2});
console.log(json);
输出
{
"person": {
"name": "Pankaj",
"age": "20",
"city": "Surat"
}
}
使用自定义JavaScript逻辑
如果您只需要处理简单的XML结构,自定义解析器可能会更好,在这里我们将手动解析XML标签和属性。
示例代码
function customXmlToJson(xml) {
const obj = {};
const regex = /<([^/]+?)>([^<]+)<\/\1>/g;
let match;
while ((match = regex.exec(xml))) {
obj[match[1]] = match[2];
}
return obj;
}
const xmlString = `<person><name>Pankaj</name><age>20</age><city>Surat</city></person>`;
console.log(JSON.stringify(customXmlToJson(xmlString)));
输出
{
"person": {
"name": "Pankaj",
"age": "20",
"city": "Surat"
}
}
处理边缘情况
- XML中的属性:如果XML具有属性(例如,<name gender="male">Pankaj</name>),则应将它们分别存储在JSON中,位于@attributes键下,以避免与标签内容冲突。
- 空标签:没有内容的标签(例如,<city />)应映射到JSON中的null。
- XML中的数组:XML中重复的标签(例如,多个<phone>条目)应转换为JSON中的数组以保留数据结构。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP