我剛開始使用Perl 1周前,我是一個編程newbee。請幫助,因爲我的公司項目依賴於此。Perl:將編輯字段保存到同一個XML文件中
現狀:
我想開一個XML文件,在這個例子中是Library.xml和編輯使用一個特定的「ISBN」號的XML文檔。找到ISBN號碼後,我想要更改與「ISBN」號碼匹配的特定書籍的頁數。
問題:
現在,我能做到上面,但我需要保存更新XML名稱相同的「library.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>
[這後應該幫你](http://stackoverflow.com/questions/10239920/using-perl-xmlsax-to-modify-xml-documents/10241803#10241803) – tuxuday 2012-04-25 07:59:57
我很好奇你在哪裏工作, d有一本Perl書籍列表。 :) – 2012-04-25 14:52:22