1 <script> 2 function validateXML(xmlContent) 3 { 4 //errorCode 0是xml正确,1是xml错误,2是无法验证 5 var xmlDoc,errorMessage,errorCode = 0; 6 // code for IE 7 if (window.ActiveXObject) 8 { 9 xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 10 xmlDoc.async="false"; 11 xmlDoc.loadXML(xmlContent); 12 13 if(xmlDoc.parseError.errorCode!=0) 14 { 15 errorMessage="错误code: " + xmlDoc.parseError.errorCode + "\n"; 16 errorMessage=errorMessage+"错误原因: " + xmlDoc.parseError.reason; 17 errorMessage=errorMessage+"错误位置: " + xmlDoc.parseError.line; 18 errorCode = 1; 19 } 20 else 21 { 22 errorMessage = "格式正确"; 23 } 24 } 25 // code for Mozilla, Firefox, Opera, chrome, safari,etc. 26 else if (document.implementation.createDocument) 27 { 28 var parser=new DOMParser(); 29 xmlDoc = parser.parseFromString(xmlContent,"text/xml"); 30 var error = xmlDoc.getElementsByTagName("parsererror"); 31 if (error.length > 0) 32 { 33 if(xmlDoc.documentElement.nodeName=="parsererror"){ 34 errorCode = 1; 35 errorMessage = xmlDoc.documentElement.childNodes[0].nodeValue; 36 } else { 37 errorCode = 1; 38 errorMessage = xmlDoc.getElementsByTagName("parsererror")[0].innerHTML; 39 } 40 } 41 else 42 { 43 errorMessage = "格式正确"; 44 } 45 } 46 else 47 { 48 errorCode = 2; 49 errorMessage = "浏览器不支持验证,无法验证xml正确性"; 50 } 51 return { 52 "msg":errorMessage, 53 "error_code":errorCode 54 }; 55 }
方法调用:
1 $(document).ready(function(){ 2 $(‘#xmlContent‘).bind(‘input propertychange‘, function() { 3 $(this).val() == "" || !validateXML($(this).val()).error_code ? $(this).removeClass("bolder") : $(this).addClass("bolder"); 4 }); 5 });
时间: 2024-10-18 10:57:42