Touko
7 months ago|views:130
格式化XML文本
// 格式化 XML 的函数
function formatXml(xml) {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xml, "application/xml");
const prettyXml = formatNode(xmlDoc.documentElement, 0);
return `<?xml version="1.0" encoding="UTF-8"?>\n${prettyXml}`;
}
function formatNode(node, level) {
const indent = " ".repeat(level);
let xml = "";
if (node.nodeType === 1) {
// 元素节点
xml += `${indent}<${node.nodeName}`;
// 遍历属性并加入节点
for (let attr of node.attributes) {
xml += ` ${attr.name}="${attr.value}"`;
}
// 检查是否只有文本子节点
const childNodes = Array.from(node.childNodes);
const hasOnlyTextChild =
childNodes.length === 1 && childNodes[0].nodeType === 3;
if (hasOnlyTextChild) {
// 只有文本子节点,保持在一行
xml += `>${childNodes[0].nodeValue.trim()}</${node.nodeName}>\n`;
} else if (childNodes.length === 0) {
// 没有子节点
xml += ` />\n`;
} else {
// 有其他子节点,换行处理
xml += ">\n";
for (let child of childNodes) {
xml += formatNode(child, level + 1); // 递归格式化子节点
}
xml += `${indent}</${node.nodeName}>\n`;
}
} else if (node.nodeType === 3) {
// 文本节点
const text = node.nodeValue.trim();
if (text) {
xml += `${indent}${text}\n`;
}
}
return xml;
}
tags:
0
1
comments:
It's deserted here, it looks like no one's been here