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"><![CDATA[qux]]>
# ^^^^
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);
$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
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With