简体   繁体   English

如何通过node.js中的XPath用xmldom更改DOM?

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

I am trying to alter a DOM structure in node.js. 我正在尝试更改node.js中的DOM结构。 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. 我可以加载XML字符串,并使用xmldom( https://github.com/jindw/xmldom )中的本机方法对其进行更改,但是当我加载XPath( https://github.com/goto100/xpath )并尝试通过该选择器更改DOM,它不起作用。

Is there another way to do this out there? 还有另一种方法可以做到这一点吗? The requirements are: 要求是:

  • Must work both in the browser and server side (pure js?) 必须在浏览器和服务器端都能工作(纯js?)
  • Cannot use eval or other code execution stuff (for security) 不能使用eval或其他代码执行工具(出于安全考虑)

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. bodyByXpath不是单个节点。 The fourth parameter to select , if true, will tell it to only return the first node; select的第四个参数(如果为true)将告诉它仅返回第一个节点;否则为false。 otherwise, it's a list. 否则,它是一个列表。

As aredridel states, .select() will return an array by default when you are selecting nodes. 作为aredridel状态,默认情况下,当选择节点时, .select()将返回一个数组。 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: 如果只想选择一个节点,也可以使用.select1()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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