Samantabhadra has asked for the wisdom of the Perl Monks concerning the following question:
I want to enrich an xml document with new elements and preserve earlier markup.
The script below achieves what I want, but I doubt that my method is safe and proper, as I circumvent LibXML's DOM in the decisive parts of the script.
Could you guide me to a better method? Is an xpath-expression with findnodes the way out?
In the example I look for, and markup, animals and their attributes.
"quick brown fox" is in a tight tag situation and I cannot but indicate it with milestones.
"lazy dog" can be tagged regularly.
Any comment on any part of the script will be very much appreciated. Thank you.
#!/usr/bin/perl # Catch the canid in # "The quick brown fox jumps over the lazy dog." use strict; use 5.010; use XML::LibXML; use List::MoreUtils qw(uniq); my $xml = "<foo>The quick br<bar>o</bar>wn <baz>f<bar>o</bar>x</baz>"; $xml .= " jumps over the lazy d<bar>o</bar>g.</foo>"; my $new_element = "canid"; my @queried = ("quick brown fox","lazy dog"); $xml = &doubtful_method($xml,$_) foreach @queried; my $dom = XML::LibXML->load_xml( string => $xml); say $dom->to_literal; my @canids = uniq map { &catch_milestone($_) } ($dom->findnodes('//canid')); say "Canids addressed: ", join ", ", @canids; sub doubtful_method { my $xml = $_[0]; my $queried = $_[1]; my $rex = join "(<.+?>)?", split //, $queried; $xml =~ s/($rex)/&evaluate_match($1)/gem; return $xml; } sub evaluate_match { my $match = $_[0]; my $out; eval { XML::LibXML->load_xml(string => "<test>".$match."</test>") }; if (ref($@)){ my $milestone = qq|<$new_element time="| . time . qq |"/>|; $out = $milestone.$match.$milestone; } else { $out = "<$new_element>$match</$new_element>"; } return $out; } sub catch_milestone { my $node = $_[0]; my ($out); if ($node->hasAttribute("time")) { my $milestone = qq|<$new_element(.+?)?time="|; $milestone.= $node->getAttribute("time") . qq|"(.+?)?>|; my $rex = $milestone . "(?<new>.+?)" . $milestone; $out = $+{new} if $dom->documentElement->toString =~ /($rex)/; $out =~ s/<.+?>//gm; } else { $out = $node->to_literal; } return $out; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: LiBXML: New markup while preserving earlier tags?
by choroba (Cardinal) on Mar 29, 2018 at 15:14 UTC | |
by Samantabhadra (Acolyte) on Jun 23, 2018 at 18:15 UTC | |
by choroba (Cardinal) on Jun 24, 2018 at 15:21 UTC | |
by Samantabhadra (Acolyte) on Jun 26, 2018 at 17:56 UTC | |
by choroba (Cardinal) on Jun 26, 2018 at 20:23 UTC | |
| |
|
Re: LiBXML: New markup while preserving earlier tags?
by Anonymous Monk on Mar 29, 2018 at 01:13 UTC | |
by Your Mother (Archbishop) on Jun 23, 2018 at 20:00 UTC |