如何使用 XML::Simple 检索标签属性? [英] How do I retrieve tag attributes with XML::Simple?

查看:36
本文介绍了如何使用 XML::Simple 检索标签属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想将 XML 中的属性检索到我的 Perl 程序中.但是,我在检索属性时遇到问题.

我正在使用 XML::Simple.

当 XML 像这样时,我可以很好地恢复信息:

<Id>17175540</Id></IdList>

使用此代码

 $data->{'DocSum'}->{'Id'};

然而,当 XML 是这样的:

一些标题</项目>

我在使用以下代码时没有取回任何数据

$data->{'DocSum'}->{'Title'};

顺便说一句,这是我从 http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=19288470

解决方案

我从您提供的那个页面中取出了 xml,将整个内容用作 XMLin 参数的字符串,并成功使用了

print $data->{DocSum}->{Item}->[5]->{content};

给出输出

<块引用>

溴苯腈在密西西比粉砂壤土中的降解.

这与德罗伯特所说的几乎相同.

而不是假设第 6 个 Item 元素是您想要的元素,而是打印 Name 属性为 'Title' 的节点的内容(然后跳出循环,因为您已经找到了您想要的内容):

foreach my $item_node (@{$data->{DocSum}->{Item}}){if($item_node->{Name} eq 'Title'){打印 $item_node->{content};最后的;}}

当然,这仍然只是查看紧接在 DocSum 下的 Item 节点,因此如果您要查找 PubType 而不是 Title,它不会被找到,因为它是 PubTypeList Item 节点的子节点.

I am simply trying to retrieve an attribute from XML into my Perl program. However, I am having problems retrieving attributes.

I am using XML::Simple.

I can recover information fine when XML is like this:

<IdList>
    <Id>17175540</Id>
</IdList>

by using this code

 $data->{'DocSum'}->{'Id'};

However, when the XML is like this:

<Item Name="Title" Type="String">
    Some Title
</Item>

I am not getting any data back when using the following code

$data->{'DocSum'}->{'Title'};

BTW, this is the link I am getting the XML from http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=19288470

解决方案

I took the xml from that page you provided, used the entire thing as a string for the argument to XMLin, and had success with

print $data->{DocSum}->{Item}->[5]->{content};

giving the output

Bromoxynil degradation in a Mississippi silt loam soil.

This is pretty much the same thing derobert was saying.

Edit:

Rather than assuming the 6th Item element is the one you are after, to print the content of the node where the Name attribute is 'Title' (and then break out of the loop since you've found what you want):

foreach my $item_node (@{$data->{DocSum}->{Item}})
{
    if($item_node->{Name} eq 'Title')
    {
        print $item_node->{content};
        last;
    }
}

Of course, this is still only looking at the Item nodes immediately under DocSum, so if you were looking for PubType instead of Title, it wouldn't be found due to that being a child of the PubTypeList Item node.

这篇关于如何使用 XML::Simple 检索标签属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆