in reply to XML::XPath and preserving CDATA fields
Getting &lt;br> instead of <br> is certainly a bug, but note that using the latest version (1.12) I get the right output though, so if you are using an earlier version you might want to upgrade.
As for XML::XPath turning the CDATA section into regular PCDATA with entities for & and <, I would think this is a design choice, the fact that there ever was a CDATA section seems to be totally ignored by XML::XPath. For XML purposes the 2 versions are equivalent, CDATA sections are just a shortcut to avoid typing a bunch of entities. That said I know for a lot of applications there is a difference between the 2, especially when you want to include regular HTML within an XML document, and I don't really like modules that don't preserve the original form of the input document, but hey,XML::XPath is so convenient, it might be worth using it and writing an extra step that restores the CDATA section, so here is my solution:
#!/usr/bin/perl -w use strict; use XML::XPath; undef $/; my $XML=<DATA>; my $xpath = XML::XPath->new('xml' => $XML); foreach my $node ($xpath->findnodes('/foo/bar/text')->get_nodelist) { my $data = your_munge_function($node->string_value); my $id = $node->getAttribute('id'); $xpath->setNodeText('/foo/bar/text[@id="' . $id . '"]', $data); } my $newXML = $xpath->findnodes_as_string('/'); # safe because XML::XPath entiti-zes > in attributes $newXML=~ s{(<text[^>]*>)(.*?)(</text>)} {$1 . cdata_ize($2) . $3}eg; print $newXML; sub your_munge_function { return "munged $_[0]"; } sub cdata_ize { my $text= shift; $text=~ s{&}{&}g; $text=~ s{<}{<}g; return "<![CDATA[$text]]>"; } __DATA__ <foo> <bar> <text id="text1>"><![CDATA[La dee da de da.<br>Foo bar baz]]></text> </bar> </foo>
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: XML::XPath and preserving CDATA fields
by Anonymous Monk on May 30, 2002 at 15:11 UTC | |
by mirod (Canon) on May 30, 2002 at 16:07 UTC | |
by mfriedman (Monk) on May 30, 2002 at 19:36 UTC |