1、JSON解析为XML
function parseJSONToXML(json) {
let xmlDoc = document.implementation.createDocument(null, '');
function parseValue(value, parentElement) {
if (Array.isArray(value)) {
for (let item of value) {
let arrayElement = xmlDoc.createElement(parentElement.tagName);
parseValue(item, arrayElement);
if (parentElement) {
parentElement.appendChild(arrayElement);
}
}
} else if (typeof value === 'object') {
parseObject(value, parentElement);
} else {
parentElement.textContent = value;
}
}
function parseObject(obj, parentElement) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
let value = obj[key];
let element = xmlDoc.createElement(key);
parseValue(value, element);
if (parentElement) {
parentElement.appendChild(element);
} else {
xmlDoc.appendChild(element);
}
}
}
}
parseObject(json, null);
let serializer = new XMLSerializer();
return '<?xml version="1.0" encoding="UTF-8"?>' + serializer.serializeToString(xmlDoc);
}
// 使用示例
let json = {
root: {
name: 'John',
age: 30,
addresses: [
{ street: 'Main St', city: 'City1' },
{ street: 'Second St', city: 'City2' }
]
}
};
let xmlString = parseJSONToXML(json);
console.log(xmlString);
2、XML解析为JSON
function parseXMLToJSON(xml) {
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(xml, 'text/xml');
function parseElement(element) {
let obj = {};
if (element.hasChildNodes()) {
let nestedElements = Array.from(element.children);
if (nestedElements.length > 0) {
nestedElements.forEach((nestedElement) => {
let key = nestedElement.tagName;
let value = parseElement(nestedElement);
if (obj.hasOwnProperty(key)) {
if (!Array.isArray(obj[key])) {
obj[key] = [obj[key]];
}
obj[key].push(value);
} else {
obj[key] = value;
}
});
} else {
obj = element.textContent;
}
}
return obj;
}
let rootNode = xmlDoc.documentElement;
let json = {};
let rootElement = parseElement(rootNode);
json[rootNode.tagName] = rootElement;
return JSON.stringify(json);
}
// 使用示例
let xmlString = '<?xml version="1.0" encoding="UTF-8"?><root><name>John</name><age>30</age><addresses><street>Main St</street><city>City1</city></addresses><addresses><street>Second St</street><city>City2</city></addresses></root>';
let json = parseXMLToJSON(xmlString);
console.log(json);
文章来源地址https://www.toymoban.com/news/detail-663842.html
文章来源:https://www.toymoban.com/news/detail-663842.html
到了这里,关于【工具】XML和JSON互相转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!