javascript - 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 替换的下降将不胜感激。
解决方案
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.
推荐阅读
- javascript - E2E - 我想知道在 it 块中允许多少期望
- outlook - Outlook 委派用户定期失去对共享日历的编辑权限
- html - 下拉问题
- google-sheets - 比较 2 列以创建另一列
- c# - 查询中的 OpenEdge/Progress DB 参数
- oracle - 当表单被其他用户打开时,如何终止 Weblogic 表单和报告中的活动会话?
- iphone - Admob ( GoogleMobileAds 8.0.0 ) iOS SDK - 未找到 GADInterstitial API,如何使用 GADInterstitialAd - 请提供示例代码?
- r - 无法将类型“闭包”强制为向量
- node.js - 有没有办法找出哪个函数不让 Node 退出?
- regex - Yahoo Finance 上的 Google Sheet Web-scraping ImportXml Xpath