Perl-XML :: LibXML-获取具有某些属性的元素 [英] Perl - XML::LibXML - getting elements that have certain attributes

查看:100
本文介绍了Perl-XML :: LibXML-获取具有某些属性的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,希望有人可以帮助您...

I have a problem I am hoping someone can help with...

我有以下示例xml结构:

I have the following example xml structure:

<library>
    <book>
       <title>Perl Best Practices</title>
       <author>Damian Conway</author>
       <isbn>0596001738</isbn>
       <pages>542</pages>
       <image src="http://www.oreilly.com/catalog/covers/perlbp.s.gif"
            width="145" height="190" />
    </book>
    <book>
       <title>Perl Cookbook, Second Edition</title>
       <author>Tom Christiansen</author>
       <author>Nathan Torkington</author>
       <isbn>0596003137</isbn>
       <pages>964</pages>
       <image src="http://www.oreilly.com/catalog/covers/perlckbk2.s.gif"
            width="145" height="190" />
    </book>
    <book>
       <title>Guitar for Dummies</title>
       <author>Mark Phillips</author>
       <author>John Chappell</author>
       <isbn>076455106X</isbn>
       <pages>392</pages>
       <image src="http://media.wiley.com/product_data/coverImage/6X/0750/0766X.jpg"
           width="100" height="125" />
    </book>
</library>

我认为应该起作用的代码:

Code that I thought should work:

use warnings;
use strict;

use XML::LibXML;

my $parser = XML::LibXML->new();
my $xmldoc = $parser->parse_file('/path/to/xmlfile.xml');

my $width = "145";

my $query = "//book/image[\@width/text() = '$width']/author/text()";

foreach my $data ($xmldoc->findnodes($query)) {
    print "Results: $data\n";
}

预期输出:

达米安·康威(Damian Conway) 汤姆·克里斯蒂安森

Damian Conway Tom Christiansen

但是我什么也得不到.

我认为这将与"book"元素中的任何"author"元素的文本内容匹配,该"book"元素还包含一个"image"元素,其属性"width"的值为145.

我敢肯定,我在这里忽略了一些非常明显的事情,但是无法弄清我做错了什么.

I'm sure I'm overlooking something very obvious here but cannot work out what I am doing wrong.

非常感谢您的帮助

推荐答案

您快到了.请注意,author不是image的子级.属性没有text()子级,您可以直接将它们的值与字符串进行比较.另外,需要toString才能打印出值而不是引用.

You were almost there. Just notice that author is not a child of image. Attributes do not have text() children, you can compare their values directly with strings. Also, toString is needed to print the values out instead of references.

#!/usr/bin/perl
use warnings;
use strict;

use XML::LibXML;

my $parser = XML::LibXML->new();
my $xmldoc = $parser->parse_file('1.xml');

my $width = "145";

my $query = "//book[image/\@width = '$width']/author/text()";

foreach my $data ($xmldoc->findnodes($query)) {
    print "Results: ", $data->toString, "\n";
}

这篇关于Perl-XML :: LibXML-获取具有某些属性的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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