从cheerio XML元素得到即时文本
使用cheerio
解析XML,考虑
<foo>this<bar>that</bar></foo>
我想只有拿到“本”当我做$('foo').text()
但我正在逐渐“thisthat”。如何限制只在元素FOO即时文本的反应如何?
对于你的问题的例子,你可以得到foo的第一个孩子的文字:
$("foo")[0].children[0].data; //'this'
相反,如果你想foo
内所有直接的文字,你可以遍历其children
和他们type
行事。片段:
function getImmediateText(str){
let retStr = "";
var $ = cheerio.load(str);
var children = $("foo")[0].children;
children.forEach(function(child){
//if type is text, add to return string
if(child.type == "text")
retStr += child.data;
})
return retStr;
}
如果您的文字是<foo>this<bar>that</bar>after</foo>
,这将返回thisafter
。你可以很容易地改变它把空格或换行符之间的“本”和“之后”如果需要的话。
从cheerio XML元素得到即时文本
使用cheerio
解析XML,考虑
<foo>this<bar>that</bar></foo>
我想只有拿到“本”当我做$('foo').text()
但我正在逐渐“thisthat”。如何限制只在元素FOO即时文本的反应如何?
对于你的问题的例子,你可以得到foo的第一个孩子的文字:
$("foo")[0].children[0].data; //'this'
相反,如果你想foo
内所有直接的文字,你可以遍历其children
和他们type
行事。片段:
function getImmediateText(str){
let retStr = "";
var $ = cheerio.load(str);
var children = $("foo")[0].children;
children.forEach(function(child){
//if type is text, add to return string
if(child.type == "text")
retStr += child.data;
})
return retStr;
}
如果您的文字是<foo>this<bar>that</bar>after</foo>
,这将返回thisafter
。你可以很容易地改变它把空格或换行符之间的“本”和“之后”如果需要的话。