2025-04-28 12:25:20 +08:00

103 lines
2.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* XML与HTML工具函数模块
* @type {module}
*/
/**
* 格式化XML字符串
* @param {string} xml - 要格式化的XML字符串
* @returns {string} 格式化后的XML字符串
*/
export function formatXml(xml) {
if (!xml) return '';
try {
// 使用DOMParser解析XML并使用XMLSerializer重新序列化
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xml, 'application/xml');
// 检查解析错误
const parseError = xmlDoc.querySelector('parsererror');
if (parseError) {
return xml; // 如果有解析错误返回原始XML
}
// 创建格式化函数
const PADDING = ' '; // 两个空格作为缩进
const reg = /(>)(<)(\/*)/g;
let pad = 0;
// 替换XML中的>< 为 >\n<
let formatted = new XMLSerializer().serializeToString(xmlDoc)
.replace(reg, '$1\n$2$3')
.split('\n');
let result = '';
// 根据标签添加缩进
formatted.forEach(line => {
// 检查是否是结束标签
if (line.match(/<\//)) {
pad--;
}
result += Array(pad + 1).join(PADDING) + line + '\n';
// 检查是否是开始标签且不是自闭合标签
if (line.match(/<[^\/].*[^\/]>$/)) {
pad++;
}
});
return result.trim();
} catch (error) {
console.error('XML格式化错误:', error);
return xml; // 如果有错误返回原始XML
}
}
/**
* 转义HTML特殊字符
* @param {string} unsafe - 需要转义的字符串
* @returns {string} 转义后的安全字符串
*/
export function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
/**
* 验证元素名称是否符合XML规范
* @param {string} name - 要验证的元素名称
* @returns {boolean} 是否是有效的XML元素名称
*/
export function isValidElementName(name) {
// XML元素名称规则:
// 1. 不能以数字或标点符号开头
// 2. 不能以xml大写、小写、混合大小写开头
// 3. 不能包含空格
// 4. 只能包含字母、数字、下划线、连字符和点
if (!name) return false;
// 检查开头是否为字母或下划线
if (!/^[a-zA-Z_]/.test(name)) {
return false;
}
// 检查是否以xml开头不区分大小写
if (/^xml/i.test(name)) {
return false;
}
// 检查是否包含有效字符
if (!/^[a-zA-Z0-9_\-\.]+$/.test(name)) {
return false;
}
return true;
}