【问题标题】:Testing Parameters of XML tag before extracting data in Perl在Perl中提取数据之前测试XML标签的参数
【发布时间】:2014-05-24 07:49:05
【问题描述】:

我正在尝试查看 XML 中的 a 标记。我的脚本一直运行到 dbReferences(一个条目有几个),但如果 'type' = "EC",我只想使用 'id'。

我正在考虑执行某种类型的 if 语句,它会在获取 id 之前查看 dbReference 的“类型”:

foreach $entry (@{$data->{entry}}) {         
        foreach $ref (@{$entry->{dbReference}}) {
            if($ref type ="EC"){
                #then print the id
            }
        }
 }

编辑: 条目 XML 将像这样格式化,连续有很多 dbReferences,需要检查:

<dbReference type="NCBI Taxonomy" id="9606"/>
<dbReference type="PubMed" id="8274401"/>
<dbReference type="EC" id="1.1.5.54"/>

有什么想法吗?

【问题讨论】:

  • yu应该写if ($ref eq "EC")
  • dbReference 有一堆参数,id、长度、类型、属性等。如何在if语句中指定我是测试类型?
  • 您能否发布一个示例输入以及您所解释的内容?
  • 我更新了主帖,对 xml 的外观进行了编辑。代码已经用 XML::Simple 进行了解析。我不确定如何访问 dbReference 的类型和 id 参数,因为它们不在标记的主体中。

标签: xml perl parsing


【解决方案1】:

您可以为此使用 XPath。此表达式为所有dbReference 元素(在任何嵌套级别)返回id,其type 属性等于EC

//dbReference[@type="EC"]/@id

代码sn-p:

use XML::LibXML;

my $dom = XML::LibXML->new->parse_file('file.xml');
my $node = $dom->findnodes('//dbReference[@type="EC"]/@id');
print 'Result: '.$node;

您可以使用额外的限制来调整表达式(例如:节点的绝对路径,或其他属性、节点位置等),以防它不返回唯一值。

【讨论】:

  • 我可以将 findnodes 方法合并到 for 循环中吗?这样我就可以将每个条目的值保持在一起。
  • 是的,但是如果您选择此解决方案,您可能也希望使用 XPath,因为它会更有效。您可以返回一组节点并在它们上循环。例如,请参阅this question 的答案。
  • 您能解释一下我将如何更改我的示例中的 registersNs 行吗,我看不到那行的意义。
  • 那是因为他的示例使用了命名空间,所以他的元素选择器需要加上前缀 (ns:tagname) 并且前缀需要映射到命名空间。如果您的 XML 文件没有声明 xmlns,则不需要。
  • 因此您在上面发布的代码应该存储所有类型为“EC”的 dbReference 标记的 id。正确的?我在代码末尾添加了 print $dom,它返回了我所有的 xml 代码
【解决方案2】:

我猜你的输入有点像

<xml>
<dbReference type="NCBI Taxonomy" id="9606"/>
<dbReference type="PubMed" id="8274401"/>
<dbReference type="EC" id="1.1.5.54"/>
<dbReference type="NCBI Taxonomy" id="9606"/>
<dbReference type="PubMed" id="8274401"/>
<dbReference type="EC" id="1.1.5.54"/>

那就试试吧:

my $ref = XMLin($String);


                #warn Dumper($ref);
       foreach $ref1 (keys %{$ref->{dbReference}}) {
            if($ref->{dbReference}->{$ref1}->{type} eq "EC"){
                #then print the id
                $ref1;
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 2013-07-12
    相关资源
    最近更新 更多