gpt4 book ai didi

javascript - 如何在 node.js 中通过 XPath 更改带有 xmldom 的 DOM?

转载 作者:行者123 更新时间:2023-11-30 17:15:40 24 4
gpt4 key购买 nike

我正在尝试更改 node.js 中的 DOM 结构。我可以加载 XML 字符串并使用 xmldom ( https://github.com/jindw/xmldom ) 中的 native 方法更改它,但是当我加载 XPath ( https://github.com/goto100/xpath ) 并尝试通过该选择器更改 DOM 时,它不起作用。

还有其他方法吗?要求是:

  • 必须同时在浏览器端和服务器端工作(纯 js?)
  • 不能使用 eval 或其他代码执行工具(出于安全考虑)

下面的示例代码展示了我今天的尝试,也许我只是错过了一些基本的东西?

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 不是单个 Node 。 select 的第四个参数,如果为真,将告诉它只返回第一个 Node ;否则,它是一个列表。

关于javascript - 如何在 node.js 中通过 XPath 更改带有 xmldom 的 DOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26167766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com