in reply to Re: XML::XPath and preserving CDATA fields
in thread XML::XPath and preserving CDATA fields

Hi mirod,

Thanks a lot for your suggestion. I think I am going to end up doing something similar to that. I was hoping there would be a more elegant solution than manually fixing the CDATA fields, though. :)

  • Comment on Re: Re: XML::XPath and preserving CDATA fields

Replies are listed 'Best First'.
Re: Re: Re: XML::XPath and preserving CDATA fields
by mirod (Canon) on May 30, 2002 at 16:07 UTC

    OK, I know everybody was waiting for me to use my hammer ;--) ... here is a solution using XML::Twig. One big caveat though is that XML::Twig's version of XPath is way, way, _WAY_ less powerful than what XML::XPath offers. No functions except string, complex sub expressions not supported, you name it. It does /foo/bar/text/* though ;--)

    #!/usr/bin/perl -w use strict; use XML::Twig; my $twig = XML::Twig->new( pretty_print => 'indented'); $twig->parse( \*DATA); # the * means that the nodes returned will be either #PCDATA # or #CDATA, this would not work if the content of text was... # not text but included sub elements foreach my $node ($twig->find_nodes('/foo/bar/text/*')) { my $data = your_munge_function($node->text); $node->set_text( $data); } $twig->print; sub your_munge_function { return "munged $_[0]"; } __DATA__ <foo> <bar> <text id="text1>"><![CDATA[La dee da de da.<br>Foo bar baz]]></text> <text id="text2>">a normal text></text> </bar> </foo>
      Wahoo! I just tested it and that solution will work perfectly. XML::Twig supports what I need to do and the code changes will be pretty minor. Thanks for your help!

      -Mike