我看到一些奇怪的行为XML::LibXML
。
下面的代码旨在添加<year>2005</year>
到两个<book>
节点。这里有什么问题吗?我尝试更改 XPath 查询 ( //library/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
my ( $age ) = XML::LibXML->new
->parse_string( '<year>2005</year>' )
->findnodes( './year' );
my @books = $xml->findnodes( '//book' );
$_->addChild( $age ) for @books;
print $xml->toString;
输出
<?xml version="1.0"?>
<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"/>
<year>2005</year></book>
</library>