Last active
April 11, 2018 12:06
-
-
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 ..
This file contains 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
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... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
live @ https://jsbin.com/seyamac/edit?js,console