解析xml以使用htmlparser2提取特定标签的文本

时间:2019-01-30 20:14:21

标签: node.js xml html-parser

我正在尝试使用node-htmlparser2并一开始就陷入困境。我有成千上万个xml文件,如下所示:

<document … loads of attribs …>
    <foo … loads of attribs …>
        <loads…> … </loads>
        <of…> … </of>
        <other…> … </other>
        <tags…> … </tags>
    </foo>
</document>

我希望<foo></foo>中的所有内容都作为单个字符串。我下面的代码有效,但是在我看来,这不是正确的方法

let isFoo = false;
let txt = '';
const p = new htmlparser.Parser({
    onopentag: function(name, attribs){
        if (name === 'foo') {
            isFoo = true;
        }
    },
    ontext: function(text){
        if (isFoo) {
            txt += text;
        }
    },
    onclosetag: function(tagname){
        if (tagname === 'foo') {
            isFoo = false;
            return txt;
        }
    }
}, {decodeEntities: true, xmlMode: true});

let data = [];
for (let file in files) {
    let record = {
        filename: file,
        filetext: p.write(file)
    }
    data.push(record);
    p.end();
}

在没有那个愚蠢的isFoo标志的情况下,有没有更好的方法可以使用htmlparser2?

1 个答案:

答案 0 :(得分:1)

这是一种可行的方法,它受DomHandler's NPM page上给出的示例以及console.log上一个丑陋的h.DomUtils的启发。

const h = require('htmlparser2');
const fs = require('fs');
const data = []; // your output

files.map((file) => { // files is assumed to be populated
  const record = {
    filename: file
  };
  data.push(record);
  const dh = new h.DomHandler((err, dom) => {
    if (err) return record.err = err;
    // DomUtils has many useful methods, most of them you know already, pick your preferred
    const e = h.DomUtils.getElementsByTagName('foo', dom)[0];
    // getText: only text nodes, getInnerHTML: everything, inner tags included
    record.filetext = h.DomUtils.getText(e);
  });
  const parser = new h.Parser(dh, {decodeEntities: true, xmlMode: true});
  fs.readFile(file, (err, content) => {
    if (err) return record.err = err;
    parser.write(content);
    parser.end();
  });
});