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 (https://github.com/jindw/xmldom), but when I load XPath (https://github.com/goto100/xpath) 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());

bodyByXpath is not a single node. The fourth parameter to select, if true, will tell it to only return the first node; otherwise, it's a list.