Javascript驗證xml格式

 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 }

方法調用:node

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 });
相關文章
相關標籤/搜索