perl – 为什么XML :: LibXML将子项添加到一个而不是另一个?
发布时间:2020-12-15 21:46:06 所属栏目:大数据 来源:网络整理
导读:我在 XML::LibXML 看到一些奇怪的行为. 以下代码旨在添加 year 2005 / year两个 book节点.这里有问题吗?我已经尝试更改XPath查询(// library / book),但结果是一样的. use strict;use warnings;use XML::LibXML;my $xml = XML::LibXML-new-parse_string( 'M
我在
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> 解决方法
添加节点会在节点与要添加节点的节点之间创建父子关系.
节点不能有两个父节点,因此当您将年节点添加到第二个节点时,它将从第一个节点中删除.您需要为每本书创建一个节点. for my $book ($xml->findnodes('//book')) { my $year = XML::LibXML::Element->new('year'); $year->appendTextNode('2005'); $book->addChild($year); } 要么 my $year = XML::LibXML::Element->new('year'); $year->appendTextNode('2005'); for my $book ($xml->findnodes('//book')) { $book->addChild( $year->cloneNode(1) ); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |