formatXml.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. String.prototype.removeLineEnd = function()
  2. {
  3. return this.replace(/(<.+?\s+?)(?:\n\s*?(.+?=".*?"))/g,'$1 $2')
  4. }
  5. function formatXml(text)
  6. {
  7. //去掉多余的空格
  8. text = '\n' + text.replace(/(<\w+)(\s.*?>)/g,function($0, name, props)
  9. {
  10. return name + ' ' + props.replace(/\s+(\w+=)/g," $1");
  11. }).replace(/>\s*?</g,">\n<");
  12. //把注释编码
  13. text = text.replace(/\n/g,'\r').replace(/<!--(.+?)-->/g,function($0, text)
  14. {
  15. var ret = '<!--' + escape(text) + '-->';
  16. //alert(ret);
  17. return ret;
  18. }).replace(/\r/g,'\n');
  19. //调整格式
  20. var rgx = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg;
  21. var nodeStack = [];
  22. var output = text.replace(rgx,function($0,all,name,isBegin,isCloseFull1,isCloseFull2 ,isFull1,isFull2){
  23. var isClosed = (isCloseFull1 == '/') || (isCloseFull2 == '/' ) || (isFull1 == '/') || (isFull2 == '/');
  24. //alert([all,isClosed].join('='));
  25. var prefix = '';
  26. if(isBegin == '!')
  27. {
  28. prefix = getPrefix(nodeStack.length);
  29. }
  30. else
  31. {
  32. if(isBegin != '/')
  33. {
  34. prefix = getPrefix(nodeStack.length);
  35. if(!isClosed)
  36. {
  37. nodeStack.push(name);
  38. }
  39. }
  40. else
  41. {
  42. nodeStack.pop();
  43. prefix = getPrefix(nodeStack.length);
  44. }
  45. }
  46. var ret = '\n' + prefix + all;
  47. return ret;
  48. });
  49. var prefixSpace = -1;
  50. var outputText = output.substring(1);
  51. //alert(outputText);
  52. //把注释还原并解码,调格式
  53. outputText = outputText.replace(/\n/g,'\r').replace(/(\s*)<!--(.+?)-->/g,function($0, prefix, text)
  54. {
  55. //alert(['[',prefix,']=',prefix.length].join(''));
  56. if(prefix.charAt(0) == '\r')
  57. prefix = prefix.substring(1);
  58. text = unescape(text).replace(/\r/g,'\n');
  59. var ret = '\n' + prefix + '<!--' + text.replace(/^\s*/mg, prefix ) + '-->';
  60. //alert(ret);
  61. return ret;
  62. });
  63. return outputText.replace(/\s+$/g,'').replace(/\r/g,'\r\n');
  64. }
  65. function getPrefix(prefixIndex)
  66. {
  67. var span = ' ';
  68. var output = [];
  69. for(var i = 0 ; i < prefixIndex; ++i)
  70. {
  71. output.push(span);
  72. }
  73. return output.join('');
  74. }