首页 > 解决方案 > Node 中的 DOMParser

问题描述

我有一个依赖 DOMParser 来解析 XML 的库实现。这在浏览器中运行良好,但显然不能与 Node.js 一起使用。我尝试将 JSDOM 与他们自己的 DOMParser 一起使用,但实际上在实现中存在细微的差异,导致我的测试失败。

我正在寻找替代 domhandler,特别是 htmlparser2。我需要做的是在 htmlparser2 中复制这种行为:

const parser = new DOMParser();
const root: Document = parser.parseFromString(xmlString, "application/xml");

我用 htmlparser2 试过这个:

const res = parseDOM(xmlString, { xmlMode: true });

但这会返回类型:Node[] 而不是 Document。我一生都无法从 htmlparser2 中找到可以从 XML 生成文档的文档,或者无法将我的 Node[] 转换为文档的方法。

似乎问题出在我的浏览器测试中(在使用 Karma 测试时模拟浏览器),由于 JSDom 代码,测试失败了。

即使有这样的代码:

let parser;
if(true){
    parser = new DOMParser();
}else{
    const JsDomParser = new JSDOM().window.DOMParser;
    parser = new JsDomParser();
}

测试失败。我必须真正注释掉 JSDOM 的东西才能让我的测试通过。可能是浏览器不兼容?

任何帮助实现这一点作为 DOMParser 替换的下降将不胜感激。

标签: javascriptnode.jsxmltypescriptdom

解决方案


In Saxon-JS we use the xml DOM implementation from https://github.com/xmldom/xmldom and it works well for us, though we haven't done a recent comparison with other options and our use is a little specialised, for example it's primarily read-only. Also we don't actually use it for parsing, for that we use github/isaacs/sax-js -- and we tweaked both products to improve the level of XML conformance in edge cases.

I don't think we've encountered any compatibility issues between xmldom under node.js, and the XML DOM implementations in the browsers.


推荐阅读