Add 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 works well for creating texts of new elements, but I'm wondering how to add CDATA without replacing XML entities: I get:

 <item desc="dddd">&lt;![CDATA[qux]]> # ^^^^ 
+5
source share
1 answer

Obviously, appendTextNode() automatically avoids the 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 function provided for this package. this is required because libxml2 handles different types of node text a little 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 $ childnode to the end of the $ node children ...

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

+5
source

Source: https://habr.com/ru/post/1209972/


All Articles