Javascript 尝试将 DOMParser 与节点 js 一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11398419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:42:55  来源:igfitidea点击:

Trying to use the DOMParser with node js

javascriptxmlnode.js

提问by Stephen D

I am running into issues when trying to use the DOMParser in my js code. In my code, I retrieve an xml file via xmlhttp.responseText soap response. I want to be able to access its elements in JSON format, so my code looks like:

尝试在我的 js 代码中使用 DOMParser 时遇到问题。在我的代码中,我通过 xmlhttp.responseText 肥皂响应检索了一个 xml 文件。我希望能够以 JSON 格式访问其元素,因此我的代码如下所示:

var xml = new DOMParser();
xml = xml.parseFromString(xmlhttp.responseText, 'text/xml');
var result = xmlToJson(xml);

I get this error message: ReferenceError: DOMParser is not defined

我收到此错误消息:ReferenceError: DOMParser is not defined

Edit: This link hasn't worked for me because my javascript isn't in the HTML page, as it is a node.js file. JavaScript DOMParser access innerHTML and other properties

编辑:此链接对我不起作用,因为我的 javascript 不在 HTML 页面中,因为它是一个 node.js 文件。 JavaScript DOMParser 访问innerHTML 等属性

采纳答案by Nino Filiu

A lot of browser functionalities, like DOM manipulations or XHR, are not available natively NodeJS because that is not a typical server task to access the DOM - you'll have to use an external library to do that.

许多浏览器功能,如 DOM 操作或 XHR,在 NodeJS 中是不可用的,因为这不是访问 DOM 的典型服务器任务——你必须使用外部库来做到这一点。

DOM capacities depends a lot on the library, here's a quick comparisons of the main tools you can use:

DOM 容量在很大程度上取决于库,以下是您可以使用的主要工具的快速比较:

  • jsdom: implements DOM level 4 which is the latest DOM standard, so everything that you can do on a modern browser, you can do it in jsdom:

    const jsdom = require("jsdom");
    const dom = new jsdom.JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
    dom.window.document.querySelector("p").textContent; // 'Hello world'
    
  • htmlparser2: same, but with enhanced performances and flexibility at the price of a more complex API:

    const htmlparser = require("htmlparser2");
    const parser = new htmlparser.Parser({
      onopentag: (name, attrib) => {
        if (name=='p') console.log('a paragraph element is opening');
      }
    }, {decodeEntities: true});
    parser.write(`<!DOCTYPE html><p>Hello world</p>`);
    parser.end();
    // console output: 'a paragraph element is opening'
    
  • cheerio: implementation of jQuery based on HTML DOM parsing by htmlparser2:

    const cheerio = require('cheerio');
    const $ = cheerio.load(`<!DOCTYPE html><p>Hello world</p>`);
    $('p').text('Bye moon');
    $.html(); // '<!DOCTYPE html><p>Bye moon</p>'
    
  • xmldom: fully implements the DOM level 2 and partially implements the DOM level 3. Works with HTML, and with XML also

  • dom-parser: regex-based DOM parser that implements a few DOM methods like getElementById. Since parsing HTML with regular expressions is a very bad ideaI wouldn't recommend this one for production.

  • jsdom: 实现 DOM level 4,这是最新的 DOM 标准,所以你可以在现代浏览器上做的一切,你可以在jsdom

    const jsdom = require("jsdom");
    const dom = new jsdom.JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
    dom.window.document.querySelector("p").textContent; // 'Hello world'
    
  • htmlparser2:相同,但以更复杂的 API 为代价提高了性能和灵活性:

    const htmlparser = require("htmlparser2");
    const parser = new htmlparser.Parser({
      onopentag: (name, attrib) => {
        if (name=='p') console.log('a paragraph element is opening');
      }
    }, {decodeEntities: true});
    parser.write(`<!DOCTYPE html><p>Hello world</p>`);
    parser.end();
    // console output: 'a paragraph element is opening'
    
  • cheerio:基于 HTML DOM 解析的 jQuery 实现htmlparser2

    const cheerio = require('cheerio');
    const $ = cheerio.load(`<!DOCTYPE html><p>Hello world</p>`);
    $('p').text('Bye moon');
    $.html(); // '<!DOCTYPE html><p>Bye moon</p>'
    
  • xmldom:完全实现 DOM 级别 2,部分实现 DOM 级别 3。适用于 HTML,也适用于 XML

  • dom-parser:基于正则表达式的 DOM 解析器,它实现了一些 DOM 方法,如getElementById. 由于使用正则表达式解析 HTML 是一个非常糟糕的主意,因此我不建议将其用于生产。

回答by Esailija

There is no DOMParserin node.js, that's a browser thing. You can try any of these modules though:

DOMParsernode.js 中没有,那是浏览器的事情。不过,您可以尝试这些模块中的任何一个:

https://github.com/joyent/node/wiki/modules#wiki-parsers-xml

https://github.com/joyent/node/wiki/modules#wiki-parsers-xml

回答by Chris Alley

You can use a Node implementation of DOMParser, such as xmldom. This will allow you to access DOMParser outside of the browser. For example:

您可以使用 DOMParser 的 Node 实现,例如xmldom。这将允许您在浏览器之外访问 DOMParser。例如:

var DOMParser = require('xmldom').DOMParser;
var parser = new DOMParser();
var document = parser.parseFromString('Your XML String', 'text/xml');

回答by Jon z

I used jsdombecause it's got a ton of usage and is written by a prominent web hero - no promises that it's behavior perfectly matches your browser (or even that every browser's behavior is the same) but it worked for me:

我使用jsdom是因为它被大量使用并且是由一位著名的网络英雄编写的 - 不能保证它的行为与您的浏览器完全匹配(甚至每个浏览器的行为都相同)但它对我有用:

const jsdom = require("jsdom")
const { JSDOM } = jsdom
global.DOMParser = new JSDOM().window.DOMParser

回答by Johannes Fahrenkrug

I really like htmlparser2. It's a fantastic, fast and lightweight library. I've created a small demo on how to use it on RunKit: https://runkit.com/jfahrenkrug/htmlparser2-demo/1.0.0

我真的很喜欢htmlparser2。这是一个很棒的、快速的和轻量级的库。我创建了一个关于如何在 RunKit 上使用它的小演示:https://runkit.com/jfahrenkrug/htmlparser2-demo/1.0.0

回答by Anjali

var DOMParser = require('xmldom').DOMParser;
var doc = new DOMParser().parseFromString(
    '<xml xmlns="a" xmlns:c="./lite">\n'+
        '\t<child>test</child>\n'+
        '\t<child></child>\n'+
        '\t<child/>\n'+
    '</xml>'
    ,'text/xml');

回答by Rafael Xavier

Not a direct answer, but depending on your application you could use JSX parser (used by React.js) https://github.com/RReverser/acorn-jsx

不是直接的答案,但根据您的应用程序,您可以使用 JSX 解析器(由 React.js 使用)https://github.com/RReverser/acorn-jsx