Skip to content

Instantly share code, notes, and snippets.

@mark05e
Last active January 27, 2022 17:49
Show Gist options
  • Save mark05e/49f3f4aee4ada73c4e7aee13dac29abb to your computer and use it in GitHub Desktop.
Save mark05e/49f3f4aee4ada73c4e7aee13dac29abb to your computer and use it in GitHub Desktop.
Parse xml string to xml
// https://stackoverflow.com/questions/11563554/how-do-i-detect-xml-parsing-errors-when-using-javascripts-domparser-in-a-cross
function parseXml(xmlString) {
var parser = new DOMParser();
// cleanup Xml
xmlString = cleanupXml(xmlString);
// attempt to parse the passed-in xml
var dom = parser.parseFromString(xmlString, 'application/xml');
if(isParseError(dom)) {
throw new Error('Error parsing XML');
}
return dom.childNodes[0];
}
function isParseError(parsedDocument) {
// parser and parsererrorNS could be cached on startup for efficiency
var parser = new DOMParser(),
errorneousParse = parser.parseFromString('<', 'application/xml'),
parsererrorNS = errorneousParse.getElementsByTagName("parsererror")[0].namespaceURI;
if (parsererrorNS === 'http://www.w3.org/1999/xhtml') {
return parsedDocument.getElementsByTagName("parsererror").length > 0;
}
return parsedDocument.getElementsByTagNameNS(parsererrorNS, 'parsererror').length > 0;
};
function cleanupXml(xmlString) {
// String Cleanup on recieved xml
xmlString = xmlString.replaceAll('\\r\\n','');
xmlString = xmlString.replaceAll('\\','');
xmlString = xmlString.replaceAll('>rn','>');
xmlString = xmlString.replaceAll('"<','<');
xmlString = xmlString.replaceAll('>"','>');
return xmlString
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment