Esteemed Monks:

I am currently using XML::XPath to extract and change some nodes in an XML document. I use code similar to the following:

my $xpath = XML::XPath->new('xml' => $XML); foreach my $node ($xpath->findnodes('/foo/bar/element')->get_nodelist) + { my $data = my_munge_function($node->as_string); my $id = $node->getAttribute('id'); $xpath->setNodeText('/foo/bar/element[@id=' . $id . ']', $data); }
I am then retrieving the modified XML thusly:
my $newXML = $xpath->findnodes_as_string('/');

NOTE: I'm not sure if all the syntax above is exactly correct - I just wrote it out from memory, since the actual code is not in front of me right now.

This all works fine, except for one thing. When I retrieve the modified XML from the $xpath object, the CDATA fields surrounding certain data have disapeared, and XML::XPath has accidentally escaped some characters that shouldn't be. As an example, the XML

<foo> <bar> <text><![CDATA[La dee da de da.<br>Foo bar baz]]></text> </bar> </foo>
Comes back as:
<foo> <bar> <text>La dee da de da.&amp;lt;br>Foo bar baz</text> </bar> </foo>
I think I know why the CDATA field disapears; the parser is returning the content of the field to XML::XPath but not the information that it is a CDATA. The problem is that this XML must then go to an XSL transformer (Sablotron, in this case) and it's broken.

I would appreciate dearly any insight into this matter.

Thanks,

-Mike


In reply to XML::XPath and preserving CDATA fields by mfriedman

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.