<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
//var jsonObj = JSON.parse(后端返回的json字符串);
//var result = JSON.stringify(jsonObj, null, 2);//格式化
String.prototype.removeLineEnd = function () {
return this.replace(/(<.+?\s+?)(?:\n\s*?(.+?=".*?"))/g, '$1 $2');
}
function formatXml(text) {
//去掉多余的空格
text = '\n' + text.replace(/(<\w+)(\s.*?>)/g,
function ($0, name, props) {
return name + ' ' + props.replace(/\s+(\w+=)/g, " $1");
}).replace(/>\s*?</g, ">\n<");
//把注釋編碼
text = text.replace(/\n/g, '\r').replace(/<!--(.+?)-->/g,
function ($0, text) {
var ret = '<!--' + escape(text) + '-->';
return ret;
}).replace(/\r/g, '\n');
//調(diào)整格式
var rgx = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg;
var nodeStack = [];
var output = text.replace(rgx, function ($0, all, name, isBegin, isCloseFull1, isCloseFull2, isFull1, isFull2) {
var isClosed = (isCloseFull1 == '/') || (isCloseFull2 == '/') || (isFull1 == '/') || (isFull2 == '/');
var prefix = '';
if (isBegin == '!') {
prefix = getPrefix(nodeStack.length);
} else {
if (isBegin != '/') {
prefix = getPrefix(nodeStack.length);
if (!isClosed) {
nodeStack.push(name);
}
} else {
nodeStack.pop();
prefix = getPrefix(nodeStack.length);
}
}
var ret = '\n' + prefix + all;
return ret;
});
var prefixSpace = -1;
var outputText = output.substring(1);
//把注釋還原并解碼,調(diào)格式
outputText = outputText.replace(/\n/g, '\r').replace(/(\s*)<!--(.+?)-->/g,
function ($0, prefix, text) {
if (prefix.charAt(0) == '\r') prefix = prefix.substring(1);
text = unescape(text).replace(/\r/g, '\n');
var ret = '\n' + prefix + '<!--' + text.replace(/^\s*/mg, prefix) + '-->';
return ret;
});
return outputText.replace(/\s+$/g, '').replace(/\r/g, '\r\n');
}
function getPrefix(prefixIndex) {
var span = ' ';
var output = [];
for (var i = 0; i < prefixIndex; ++i) {
output.push(span);
}
return output.join('');
}
// 2) 、調(diào)用方法進行格式化
var result = formatXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<InterfaceFile><statues></statues></InterfaceFile>");
console.log(result)
</script>
格式化xml
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。