简体   繁体   中英

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.

As aredridel states, .select() will return an array by default when you are selecting nodes. So you would need to obtain your node from that array.

You can also use .select1() if you only want to select a single node:

var bodyByXpath = xpath.select1('//*[@id = "test"]', doc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM