Skip to content

Instantly share code, notes, and snippets.

@4leem
Created June 24, 2020 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 4leem/3f61f05759b6be62868b8e3e92a9dcf2 to your computer and use it in GitHub Desktop.
Save 4leem/3f61f05759b6be62868b8e3e92a9dcf2 to your computer and use it in GitHub Desktop.
Validate XML with JavaScript code
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