这里似乎有些奇怪。
在下面的示例中,我通过 XPath 查询 ( //book/isbn/text()
) 访问文本节点。有text()
必要强迫XML::LibXML
我使用这些XML::LibXML::Text
方法。
但是,要到达父节点,我必须调用该parentNode
方法两次才能获得真正的父节点(<book>
在这种情况下):
use strict;
use warnings;
use XML::LibXML;
my $xml = XML::LibXML->new->parse_string( << 'MAIN' );
<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>
</library>
MAIN
foreach my $isbn ( $xml->findnodes( '//book/isbn/text()' ) ) {
# Do something with $isbn->setData()
my $book = $isbn->parentNode->parentNode; # My daddy's daddy is my daddy?
print $book->toString;
}
输出
<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>
所以:
- 假设
//isbn
和//isbn/text()
是同一个节点,我对 XML 节点的理解是否不正确,或者 XML::LibXML
这是'sparentNode
方法中的错误吗?