【问题标题】:nodejs using cheerio parsing xml returns empty CDATAnodejs使用cheerio解析xml返回空CDATA
【发布时间】:2013-03-06 12:24:54
【问题描述】:

我在nodejs 中使用cheerio 来解析一些RSS 提要。我正在抓取所有将它们放入数组中的项目。我正在使用 3 个测试提要,每个“项目”元素都有一个“描述”子元素。在其中一个提要中,整个“描述”被包装为 CDATA,我无法获得它的价值。这是一个缩写代码sn-p

//Open the xml document with cheerio
$ = cheerio.load(arrXmlDocs[i],{ ignoreWhitespace : true, xmlMode : true});

//Loop through every item
$('item').each(function(i, xmlItem){

    //array to hold each item being converted into an array
    var tempArray = [];

    //Loop through each child of <item>
    $(xmlItem).children().each(function(i, xmlItem){
        //Get the name 
        tempArray[$(this)[0].name] = $(this).text();
    }

}

正如预期的那样,两个没有 CDATA 的 rss 提要给了我一个这样的数组

[
    [
        name: 'name of episode',
        description:'description of episode',
        pubdate: 'published date'
    ],
    [
        name: 'name of episode',
        description:'description of episode',
        pubdate: 'published date'
    ]
]

带有 CDATA 描述的提要看起来像这样

    [
        name: 'name of episode',
        pubdate: 'published date'
    ],

所以我的问题是:为什么 Cheerio 不返回包含在 CDATA 中的值/我怎样才能让它返回这些值。

【问题讨论】:

  • 你能把你在这里问的更清楚吗?
  • 已更新以更清楚地提出问题。

标签: javascript xml node.js cdata cheerio


【解决方案1】:

我是 a known issue (related) 和cheerio。在您的情况下,它还无法使用CDATA 从 XML 中创建正确的树。我知道这是一个令人失望的答案,它是 WIP。

正在处理中,同时,您可以使用正则表达式删除CDATA

arrXmlDocs[i].replace(/<!\[CDATA\[([\s\S]*?)\]\]>(?=\s*<)/gi, "$1");

这是一个示例链接jsfiddle

虽然这不是一个理想的解决方案,但在他们解决这个问题之前应该足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多