如何使用 <rss> XML::LibXML 解析标记以查找 xmlns 定义


播客

定义其rss提要似乎没有一致的方式。遇到了一个对 RSS 使用不同架构定义的。

使用 XML::LibXML 扫描 RSS URL 中的 xmlnamespace 的最佳方法是什么

例如

一个源可能是

<rss 
    xmlns:content="http://purl.org/rss/1.0/modules/content/" 
    xmlns:wfw="http://wellformedweb.org/CommentAPI/" 
    xmlns:dc="http://purl.org/dc/elements/1.1/" 
    xmlns:atom="http://www.w3.org/2005/Atom" 
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" 
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

另一个可能是

<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"version="2.0"
     xmlns:atom="http://www.w3.org/2005/Atom">

我想在我的脚本中包含对所有正在使用的命名空间的评估,以便在解析 rss 时可以跟踪适当的字段名称。

还不确定会是什么样子,因为我不确定这个模块是否有能力执行我想要的<rss>标签属性雾化。

我不确定我是否确切地了解您正在寻找哪种输出,但XML::LibXML确实能够列出命名空间:

use warnings;
use strict;
use XML::LibXML;
my $dom = XML::LibXML->load_xml(string => <<'EOT');
<rss 
    xmlns:content="http://purl.org/rss/1.0/modules/content/" 
    xmlns:wfw="http://wellformedweb.org/CommentAPI/" 
    xmlns:dc="http://purl.org/dc/elements/1.1/" 
    xmlns:atom="http://www.w3.org/2005/Atom" 
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" 
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">
</rss>
EOT
for my $ns ($dom->documentElement->getNamespaces) {
    print $ns->getLocalName(), " / ", $ns->getData(), "n";
}

输出:

content / http://purl.org/rss/1.0/modules/content/
wfw / http://wellformedweb.org/CommentAPI/
dc / http://purl.org/dc/elements/1.1/
atom / http://www.w3.org/2005/Atom
sy / http://purl.org/rss/1.0/modules/syndication/
slash / http://purl.org/rss/1.0/modules/slash/

我知道OP已经接受了答案。但为了完整起见,应该提到的是,在 DOM 弹性上进行搜索的推荐方法是使用 XML::LibXML::XPathContext:

#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML;
my @examples = (
    <<EOT
<rss xmlns:atom="http://www.w3.org/2005/Atom">
  <atom:test>One Ring to rule them all,</atom:test>
</rss>
EOT
    ,
    <<EOT
<rss xmlns:a="http://www.w3.org/2005/Atom">
  <a:test>One Ring to find them,</a:test>
</rss>
EOT
    ,
    <<EOT
<rss xmlns="http://www.w3.org/2005/Atom">
  <test>The end...</test>
</rss>
EOT
    ,
);
my $xpc = XML::LibXML::XPathContext->new();
$xpc->registerNs('atom', 'http://www.w3.org/2005/Atom');
for my $example (@examples) {
    my $dom = XML::LibXML->load_xml(string => $example)
        or die "XML: $!n";
    for my $node ($xpc->findnodes("//atom:test", $dom)) {
        printf("%-10s: %sn", $node->nodeName, $node->textContent);
    }
}
exit 0;

即,您为您感兴趣的命名空间分配本地命名空间前缀。

输出:

$ perl dummy.pl
atom:test : One Ring to rule them all,
a:test    : One Ring to find them,
test      : The end...

最新更新