平時用 Emeditor 檢視 XML 文件時,最讓人頭疼的就是排版雜亂、標籤擠成一團,根本看不清結構。為了解決這個困擾,這裡提供一個能自動整理 XML 格式的 Emeditor 巨集,下載點:formatXml.rar(1,021.00 bytes)。
下面這段就是網頁版的 JavaScript 格式化 XML 程式碼,直接複製即可使用:
複製程式碼 程式碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv=content-type content="text/html; charset=UTF-8">
<title>Xml格式化工具</title>
<script type="text/javascript">
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');
//調整格式
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 == '!')\n {
prefix = getPrefix(nodeStack.length);
}
else
{
if(isBegin != '/')
{
prefix = getPrefix(nodeStack.length);
if(!isClosed)
{
nodeStack.push(name);
}\n }\n else
{
nodeStack.pop();
prefix = getPrefix(nodeStack.length);
}
}
var ret = '\n' + prefix + all;
return ret;
});
var prefixSpace = -1;
var outputText = output.substring(1);
//把注釋還原並解碼,調格式
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('');
}
function btnFormat_click()
{
var $ = document.getElementById;
$('output').value = formatXml($('input').value);
}
</script>
</head>
<body>
<textarea id="input" style="width:100%;height:45%;"></textarea>
<div style="margin:0px auto;"><input type="button" id="btnFormat" onclick="btnFormat_click()" value="格式化" style="width:50%;height:10%;"/></div>
<textarea id="output" style="width:100%;height:45%;"></textarea>
</body>
</html>
這段腳本的核心思路是先正規化標籤內的屬性空格,再把每個標籤拆成獨立一行,接著透過一個節點堆疊(nodeStack)追蹤嵌套層級,最後依深度補上對應的縮排,讓整份 XML 一目了然。註釋部分則先編碼暫存、格式化後再還原,避免特殊字元干擾排版。