XML (eXtensible Markup Language) 和 JSON (JavaScript Object Notation) 都是常用的数据交换格式,但它们的结构和语法有很大不同。将XML解析为JSON是一种常见的数据转换需求,特别是在现代Web开发中,JSON已成为更受欢迎的数据格式。
const xml2js = require('xml2js');
const parser = new xml2js.Parser({ explicitArray: false });
// XML字符串示例
const xml = `
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>`;
parser.parseString(xml, (err, result) => {
if (err) {
console.error(err);
} else {
console.log(JSON.stringify(result, null, 2));
}
});
function xmlToJson(xmlString) {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
function parseNode(node) {
const obj = {};
// 处理属性
if (node.attributes && node.attributes.length > 0) {
obj["@attributes"] = {};
for (let i = 0; i < node.attributes.length; i++) {
const attr = node.attributes[i];
obj["@attributes"][attr.nodeName] = attr.nodeValue;
}
}
// 处理子节点
if (node.childNodes && node.childNodes.length > 0) {
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
if (child.nodeType === 1) { // 元素节点
const nodeName = child.nodeName;
if (typeof obj[nodeName] === "undefined") {
obj[nodeName] = parseNode(child);
} else {
if (!Array.isArray(obj[nodeName])) {
obj[nodeName] = [obj[nodeName]];
}
obj[nodeName].push(parseNode(child));
}
} else if (child.nodeType === 3 && child.nodeValue.trim() !== "") { // 文本节点
obj["#text"] = child.nodeValue.trim();
}
}
}
return Object.keys(obj).length === 0 ? "" : obj;
}
return parseNode(xmlDoc.documentElement);
}
// 使用示例
const xmlString = `<note><to>John</to><from>Jane</from><heading>Reminder</heading><body>Don't forget the meeting!</body></note>`;
console.log(JSON.stringify(xmlToJson(xmlString), null, 2));
import json
import xmltodict
# XML字符串
xml_string = """
<employees>
<employee id="101">
<name>John Doe</name>
<position>Software Engineer</position>
<department>IT</department>
</employee>
<employee id="102">
<name>Jane Smith</name>
<position>Product Manager</position>
<department>Product</department>
</employee>
</employees>
"""
# 转换为字典
data_dict = xmltodict.parse(xml_string)
# 转换为JSON
json_data = json.dumps(data_dict, indent=4)
print(json_data)
import org.json.JSONObject;
import org.json.XML;
public class XmlToJson {
public static void main(String[] args) {
String xmlString = "<root><name>John</name><age>30</age><city>New York</city></root>";
// 转换为JSON
JSONObject jsonObject = XML.toJSONObject(xmlString);
String jsonString = jsonObject.toString(4); // 缩进4个空格
System.out.println(jsonString);
}
}
问题:XML属性在转换为JSON时丢失或处理不当。
解决方案:使用约定好的格式表示属性,如@attribute
表示法。
问题:当XML中同一元素出现多次时,可能被错误地处理为对象而非数组。
解决方案:在解析器配置中明确指定是否强制数组(如xml2js中的explicitArray
选项)。
问题:XML命名空间可能导致JSON结构复杂化。
解决方案:可以选择忽略命名空间或使用特定的命名空间处理策略。
问题:大XML文件可能导致内存问题。
解决方案:使用流式解析器(如SAX解析器)逐步处理XML。
通过上述方法和注意事项,您可以有效地将XML数据解析为JSON格式,满足现代应用开发的需求。
没有搜到相关的文章