在 EmEditor 中檢視 XML 檔案時,常因縮排混亂難以閱讀。本文提供一個可直接在網頁執行的 JavaScript XML 格式化工具,核心邏輯為一段自包含的格式化函式,可整合至編輯器巨集或獨立網頁工具。
formatXml(text)函式流程分三階段:
>< 之間換行。<!-- ... --> 內容以 escape() 編碼,避免後續正則誤判。function formatXml(text) {
// 1. 正規化空白與換行
text = '\n' + text.replace(/(<\w+)(\s.*?>)/g, function($0, name, props) {
return name + ' ' + props.replace(/\s+(\w+=)/g, " $1");
}).replace(/>\s*?</g, ">\n<");
// 2. 註解暫存編碼
text = text.replace(/\n/g, '\r').replace(/<!--(.+?)-->/g, function($0, txt) {
return '<!--' + escape(txt) + '-->';
}).replace(/\r/g, '\n');
// 3. 節點堆疊縮排
var rgx = /\n(<(([^?]).+?)(?:\s|\s*?>|\s*?(/)>)(?:.*?(?:(?:(/)>)|(?:<\/(.+?)>)))?)/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);
}
}
return '\n' + prefix + all;
});
// 4. 還原註解並微調縮排
var outputText = output.substring(1);
outputText = outputText.replace(/\n/g, '\r').replace(/(\s*)<!--(.+?)-->/g, function($0, prefix, txt) {
if (prefix.charAt(0) == '\r') prefix = prefix.substring(1);
txt = unescape(txt).replace(/\r/g, '\n');
return '\n' + prefix + '<!--' + txt.replace(/^\s*/mg, prefix) + '-->';
});
return outputText.replace(/\s+$/g, '').replace(/\r/g, '\r\n');
}
function getPrefix(level) {
var span = ' ';
var arr = [];
for (var i = 0; i < level; ++i) arr.push(span);
return arr.join('');
}
完整 HTML 頁面包含輸入區、輸出區與格式化按鈕,引用 jQuery 綁定點擊事件:
<textarea id="input" style="width:100%;height:300px"></textarea>
<button onclick="btnFormat_click()">格式化</button>
<textarea id="output" style="width:100%;height:300px"></textarea>
<script>
function btnFormat_click() {
var $ = document.getElementById;
$('output').value = formatXml($('input').value);
}
</script>
DOMParser + 遞迴序列化,相容性更佳。