Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a CDATA with XML::LibXML appendTextNode() AS-IS

I use this code to create a new node with the expected output:

<item desc="desc foobar"><![CDATA[qux]]></item>

the code :

open my $fh, "<", $xml_file;
binmode $fh;
my $parser = XML::LibXML->new();
my $doc = $parser->load_xml(IO => $fh);

# create a new node in XML file
my $root = $doc->getDocumentElement();
my $new_element = $doc->createElement("item");
# FIXME
$new_element->appendTextNode(sprintf '<![CDATA[%s]]>', join "\n", @input);
$new_element->setAttribute('desc', $desc);
$root->appendChild($new_element);

close $fh;

open my $out, '>', $xml_file;
binmode $out;
$doc->toFH($out);

close $out;

it work well to create new elements texts, but I wonder how to add CDATA without the XML entities substitution : I get :

<item desc="dddd">&lt;![CDATA[qux]]>
#                 ^^^^
like image 894
MevatlaveKraspek Avatar asked Dec 27 '14 23:12

MevatlaveKraspek


1 Answers

It's apparent that appendTextNode() automatically escapes problematic characters in text nodes. This is what you should do:

my $cdata_node = XML::LibXML::CDATASection->new(
    join "\n", @input
);

$new_element->appendChild($cdata_node);

XML::LibXML::CDATASection

 $node = XML::LibXML::CDATASection->new( $content );

The constructor is the only provided function for this package. It is required, because libxml2 treats the different text node types slightly differently.

The class inherits from XML::LibXML::Node

http://search.cpan.org/dist/XML-LibXML/lib/XML/LibXML/CDATASection.pod

XML::LibXML::Node

$childnode = $node->appendChild( $childnode );

The function will add the $childnode to the end of $node's children...

http://search.cpan.org/~shlomif/XML-LibXML-2.0117/lib/XML/LibXML/Node.pod

like image 141
7stud Avatar answered Sep 27 '22 22:09

7stud