【发布时间】:2019-01-30 20:14:21
【问题描述】:
我正在尝试 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?
【问题讨论】:
标签: node.js xml html-parser