Chazg76
Chazg76

Reputation: 649

XML Twig: update single entry

I have an XML file with a large number of identical tags having different attributes. I need to find ONLY ONE of the tags that contains a specified attribute and update the associated value then save the information so that the new file containing the information is identical to the original with just the amended tag value updated. I am using XML Twig and wondered the quickest way to do this. I've seen the finish and finish_print methods but cannot get them to work. I think these methods are associated with twig_handlers, which is the method I currently use. However loading the whole document might be quicker when dealing with this type of problem. The files can be loaded into memory if required as they are not too large. My only real concern at the moment is the time taken to perform the operation.

Any help much appreciated.

Upvotes: 1

Views: 66

Answers (1)

Sobrique
Sobrique

Reputation: 53478

Time will purely be a function of serialising your XML.

IMO twig_handlers are primarily useful for incremental parsing of large XML, and potentially for doing in-place editing. If your XML isn't large, then just loading into memory is the way forward and less confusing.

As for finding and replacing - xpath is the tool for the job.

E.g. if you want to find:

<element name="fish">
  <value>42</value>
</element>

Then you could locate this within your XML via:

foreach my $elt ( $xml -> get_xpath('//element[@name="fish"]') ) { 
  $elt -> print; 
}

You'd then modify this how you like rather than just print it, and then simply print the whole XML doc to a new file.

If your memory available is > 10x the document size, loading into memory is the way to go.

Upvotes: 4

Related Questions