user628181
user628181

Reputation: 11

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 last 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 .= "$_";

Upvotes: 1

Views: 746

Answers (2)

ap2cu
ap2cu

Reputation: 69

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.

Upvotes: 1

daxim
daxim

Reputation: 39158

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.

Upvotes: 3

Related Questions