开发者

How to copy and edit XML file in Perl?

I'm copying the contents of an XML file into another XML file, on which this is the las开发者_如何学Got line:

</references></resume></xpath>  

I should only write upto </resume>, not </xpath>.

How to achieve that in Perl? Can I use a regular expression?

This is the command that I use to print the output:

$out_content .= "$_";


It appears you are assembling pieces of XML into a larger one by string concatenation. Don't do it, it is error-prone. Instead, rely on a real XML toolkit that understands the complexity involved.

For example, XML::Twig comes with the tools xml_split and xml_merge that easily do what you want.


There is 2 ways to do it:

  • Bad but fast way: use regex

 $outContent = $contentOfOldXmlFile;
 $outContent =~ s#^.*<xpath>((.|\n)*)</xpath>$#$1#;
  • Correct way: use XML::DOM library

use XML::DOM;
use XML::XQL; 
use XML::XQL::DOM; 

eval {
  my $xml=new XML::DOM::Parser->parsefile($yourFilename);
  my $outContent = "";
  for($xml->xql(qq(//resume))) {
    $outContent .= $_->toString();
  }
  $xml->dispose();
};
print "ERROR:$@\n" if $@;

And then you have the new content into $outContent that you can print or write to the file you want.

Preferably use the XML::DOM API to have the content you want ( with $node->toString() )instead of concatenating pieces of strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜