代码如下:
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>xml格式化</title>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<style>
body { margin:0; font-family:"微软雅黑"; font-size:12px; }
table { border-collapse:collapse; }
table .tdLeft { 150px; text-align:right; line-height:30px;}
table .tdRight { 400px; }
table textarea { 400px; height:100px; }
#showXml { margin-left:150px; 400px; height:400px; }
</style>
<script type="text/javascript">
$(document).ready(function(){
text = $('#xmlContent').val();
//去掉多余的空格
text = '
' + text.replace(/(<w+)(s.*?>)/g,function($0, name, props)
{
return name + ' ' + props.replace(/s+(w+=)/g," $1");
}).replace(/>s*?</g,">
<");
//把注释编码
text = text.replace(/
/g,'
').replace(/<!--(.+?)-->/g,function($0, text)
{
var ret = '<!--' + escape(text) + '-->';
return ret;
}).replace(/
/g,'
');
//调整格式
var rgx = /
(<(([^?]).+?)(?: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 = '
' + prefix + all;
return ret;
});
var prefixSpace = -1;
var outputText = output.substring(1);
//把注释还原并解码,调格式
outputText = outputText.replace(/
/g,'
').replace(/(s*)<!--(.+?)-->/g,function($0, prefix, text)
{
if(prefix.charAt(0) == '
')
prefix = prefix.substring(1);
text = unescape(text).replace(/
/g,'
');
var ret = '
' + prefix + '<!--' + text.replace(/^s*/mg, prefix ) + '-->';
return ret;
});
alert(outputText);
outputText= outputText.replace(/s+$/g,'').replace(/
/g,'
');
$('#showXml').val(outputText);
function getPrefix(prefixIndex)
{
var span = ' ';
var output = [];
for(var i = 0 ; i < prefixIndex; ++i)
{
output.push(span);
}
return output.join('');
}
});
</script>
</head>
<body>
<table>
<tr>
<td class="tdLeft" nowrap >请输入要展示的Xml:</td>
<td class="tdRight" ><textarea id="xmlContent"><?xml version="1.0" encoding="UTF-8"?><PARAM><DBID>35</DBID><SEQUENCE>atgtca</SEQUENCE><MAXNS>10</MAXNS><MINIDENTITIES>90</MINIDENTITIES><MAXEVALUE>10</MAXEVALUE><USERNAME>admin</USERNAME><PASSWORD>111111</PASSWORD><TYPE>P</TYPE><RETURN_TYPE>2</RETURN_TYPE></PARAM>
</textarea></td>
</tr>
<tr style="display:none">
<td class="tdLeft"> </td>
<td class="tdRight"><input type="button" value="格式化Xml" onClick="showXml()"></td>
</tr>
</table>
<div id="container">
</div>
<textarea id="showXml" >
</textarea>
</body>
</html>
效果图如下: