我一周前才开始使用 Perl,我是一名编程新手。请帮助,因为我的公司项目依赖于此。
情况:
我想打开一个 XML 文件,在本例中是 Library.xml 并使用特定的“ISBN”编号编辑 XML 文档。找到 ISBN 编号后,我想更改具有匹配“ISBN”编号的特定书籍的页数。
问题:
现在,我可以执行上述操作,但是,我需要以相同的名称“library.xml”保存更新的 XML,并保持原始 XML 文档的 XML 结构。这就是我难住的地方。我尝试过使用 XML::DUMPER 和 XML::TWIG 以及可能其他人,但都失败了。
原始 XML 文档:
library.XML 如下所示:
<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/07645510/076455106X.jpg"
width="100" height="125" />
</book>
</library>
编码:
以下是我试图操纵但没有成功的代码。
#!/usr/bin/perl
use strict;
use warnings;
#use XML::Simple qw(:strict);
use XML::LibXML;
use XML::Dumper;
my $dump = new XML::Dumper;
my $perl = ' ';
my $xml = $dump->pl2xml( $perl );
my $filename = 'library.xml';
my $isbn = '0596001738';
my $parser = XML::LibXML->new();
my $doc = $parser->parse_file($filename);
my $query = "//book[isbn = '$isbn']/pages/text()";
my($node) = $doc->findnodes($query);
$node->setData('99999');
$perl = $doc->toString;
$xml = $dump->pl2xml( $perl, "library.xml" );
print $doc->toString;
输出:
以下是我的输出。输出与原始 XML 文档不同。
<perldata>
<scalar><xml version="1.0" encoding="UTF-8">
<library>
<book>
<title>Perl Best Practices</title>
<author>Damian Conway</author>
<isbn>0596001738</isbn>
<pages>99999</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/07645510/076455106X.jpg" width="100" height="125"/>
</book>
</library>
</scalar>
</perldata>