Created
June 24, 2020 05:21
-
-
Save 4leem/3f61f05759b6be62868b8e3e92a9dcf2 to your computer and use it in GitHub Desktop.
Validate XML with JavaScript code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var xt = "", h3OK = 1; | |
function checkErrorXML(x) { | |
xt = ""; | |
h3OK = 1; | |
checkXML(x); | |
} | |
function checkXML(n) { | |
var l, i, nam; | |
nam = n.nodeName; | |
if (nam == "h3") { | |
if (h3OK == 0) { | |
return; | |
} | |
h3OK = 0; | |
} | |
if (nam == "#text") { | |
xt = xt + n.nodeValue + "\n"; | |
} | |
l = n.childNodes.length; | |
for (i = 0; i < l; i++) { | |
checkXML(n.childNodes[i]); | |
} | |
} | |
function validateXML(xml) { | |
// code for IE | |
if (window.ActiveXObject) { | |
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); | |
xmlDoc.async = false; | |
xmlDoc.loadXML(xml); | |
if (xmlDoc.parseError.errorCode != 0) { | |
txt = "Error Code: " + xmlDoc.parseError.errorCode + "\n"; | |
txt = txt + "Error Reason: " + xmlDoc.parseError.reason; | |
txt = txt + "Error Line: " + xmlDoc.parseError.line; | |
alert(txt); | |
} else { | |
alert("No errors found"); | |
} | |
} | |
// code for Chrome, Firefox etc. | |
else if (document.implementation && document.implementation.createDocument) { | |
var parser = new DOMParser(); | |
var text = xml; | |
var xmlDoc = parser.parseFromString(text, "text/xml"); | |
if (xmlDoc.getElementsByTagName("parsererror").length > 0) { | |
checkErrorXML(xmlDoc.getElementsByTagName("parsererror")[0]); | |
alert(xt); | |
} else { | |
alert("No errors found"); | |
} | |
} else { | |
alert("Your browser cannot handle this script"); | |
} | |
} | |
var xml = "<xml><name>supun</name><age>23<year>1111</year></xml>"; | |
validateXML(xml); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment