Get All XML Nodes - Javascript
Get the list of All possible XML Nodes using - Javascript
by maheshBongani
HTML
<div id="banner-message">
<p id="textDisplay">Hello World</p>
<button onclick="getAllXMLNodes()">
getAllXMLNodes();
</button>
<button onclick="getStructredXMLfromNodes()">
getStructredXMLfromNodes();
</button>
</div>
JavaScript
function getAllXMLNodes() {
var allNodes = [];
var i = 0;
function getPaths($node, parentPath) {
parentPath += $node.nodeName + '/';
var node = getNode(i++, parentPath);
//allNodes.push(node);
debugger;
//arr.push(parentPath);
if ($node.children) {
for (let i = 0; i < $node.children.length; i++) {
let childNode = getPaths($node.children[i], parentPath);
node.subs.push(childNode);
}
}
return node;
}
function getNodeAsXMLObject(text) {
var parser, xmlDoc;
parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");
console.log(xmlDoc);
return xmlDoc;
}
function getNode(id, title) {
return {
id: id,
title: title,
subs: []
};
}
var xml = `<Parcels>
<Parcel>
<Weight>0</Weight>
<Pieces>1</Pieces>
<Barcode />
<Reference2 />
<Description />
<Type>2</Type>
<MiscData />
</Parcel>
</Parcels>`;
var paths = getPaths(getNodeAsXMLObject(xml).children[0], '');
document.getElementById('textDisplay').value = JSON.stringify(paths);
console.log(paths);
alert(JSON.stringify(paths));
}
function getStructredXMLfromNodes() {
/* https: //stackoverflow.com/questions/26295599/creating-dynamic-xml-tree-based-on-the-xpath-value */
function addElementByPath(parent, path, value) {
var node = parent;
var parts = path.split(/\//);
var dom = parent.ownerDocument;
var existingNode;
for (var i = 0; i < parts.length; i++) {
existingNode = dom.evaluate(
parts[i], node, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null
).singleNodeValue;
if (existingNode) {
node = existingNode;
} else {
node = node.appendChild(dom.createElement(parts[i]));
}
}
node.appendChild(dom.createTextNode(value));
}
var paths = [
...