Skip to content

Instantly share code, notes, and snippets.

@tbremer
Last active February 21, 2018 00:25
Show Gist options
  • Save tbremer/d36257c7687bd89e2c7dc2ce401be86e to your computer and use it in GitHub Desktop.
Save tbremer/d36257c7687bd89e2c7dc2ce401be86e to your computer and use it in GitHub Desktop.
XML Parsing
// create Document tree from XML tree
const XML = `<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>`;
const MAP = {
note: 'section',
to: 'em',
from: 'em',
heading: 'h1',
body: 'p',
}
const dom = xmlToDom(XML, MAP);
console.log('dom:', dom);
// Remove all nodes
while (document.body.firstChild) document.body.removeChild(document.body.firstChild)
// append new node
document.body.appendChild(dom);
function createNode (name) { return document.createElement(name); }
function createText (str) { return document.createTextNode(str); }
function appendNodes(parent, ...children) {
children.map(cn => appendNode(parent, cn));
return parent;
}
function appendNode(parent, child) {
parent.appendChild(child);
return parent;
}
function buildNodes(map, ...nodes) { return nodes.map(n => buildNode(n, map)); }
function buildNode(protoNode, map) {
const isText = protoNode.nodeType === 3;
const node = isText ? createText(protoNode.nodeValue) : createNode(map[protoNode.nodeName.toLowerCase()]);
if (!isText) protoNode.childNodes.forEach(cn => appendNode(node, buildNode(cn, map)));
return node;
}
function xmlToDom(xml, map) {
const fragment = document.createDocumentFragment();
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xml, 'text/xml');
return appendNodes(fragment, ...buildNodes(map, ...xmlDoc.childNodes));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment