Skip to content

Instantly share code, notes, and snippets.

@teswar
Last active April 11, 2018 12:06
Show Gist options
  • Save teswar/2965741eaecba7fc1790e76a189eae38 to your computer and use it in GitHub Desktop.
Save teswar/2965741eaecba7fc1790e76a189eae38 to your computer and use it in GitHub Desktop.
Deserializing and Serializing with XMLDocument | Parsing and XMLDocument from its string representation, cloning its inner element and appending to its parent ..
class XMLHelper {
static isValid(xmlDocument) {
return (xmlDocument && !xmlDocument.getElementsByTagName('parsererror').length);
}
static deserialize(xmlString) {
return (new DOMParser()).parseFromString(xmlString, "application/xml");
}
static serialize(xmlDocument) {
return (new XMLSerializer()).serializeToString(xmlDocument);
}
}
var xmlString = `<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<cd>
<title>empire burlesque</title>
<artist>bob dylan</artist>
<country>usa</country>
<company>columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>hide your heart</title>
<artist>bonnie tyler</artist>
<country>uk</country>
<company>cbs records</company>
<price>9.90</price>
<year>1988</year>
</cd>
</catalog>`;
function doTheThing(xmlString){
var node = null, doc = XMLHelper.deserialize(xmlString);
if(!XMLHelper.isValid(doc)) {
return console.log((node = doc.querySelector('parsererror')) ? node.textContent : 'error while parsing xml');
}
(node = doc.querySelector('catalog cd')) && (node = node.parentNode.appendChild(node.cloneNode(true))) && (node.id = (new Date()).getTime());
doc = XMLHelper.serialize(doc);
console.log(doc);
}
doTheThing(); // error..
doTheThing(xmlString); // success...
@teswar
Copy link
Author

teswar commented Apr 11, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment