Thursday, 2 October 2014

How to alter DOM with xmldom by XPath in node.js?



I am trying to alter a DOM structure in node.js. I can load the XML string and alter it with the native methods in xmldom (http://ift.tt/MDNNwM), but when I load XPath (http://ift.tt/15eK2RS) and try to alter the DOM via that selector, it does not work.


Is there another way to do this out there? The requirements are:



  • Must work both in the browser and server side (pure js?)

  • Cannot use eval or other code execution stuff (for security)


Example code to show how I am trying today below, maybe I simply miss something basic?



var xpath = require('xpath'),
dom = require('xmldom').DOMParser;

var xml = '<!DOCTYPE html><html><head><title>blah</title></head><body id="test">blubb</body></html>';
var doc = new dom().parseFromString(xml);

var bodyByXpath = xpath.select('//*[@id = "test"]', doc);
var bodyById = doc.getElementById('test');
var h1 = doc.createElement('h1').appendChild(doc.createTextNode('title'));

// Works fine :)
bodyById.appendChild(h1);

// Does not work :(
bodyByXpath.appendChild(h1);

console.log(doc.toString());

No comments:

Post a Comment