I'm using libxml2 to read/write xml files. Now I'm trying to write a CDATA node.
Here is what I tried:
nodePtr = xmlNewChild( parentPtr, NULL, "foo", NULL );
xmlNodeSetContentLen( nodePtr, "<![CDATA[\nTesting 1 < 2\n]]>", len );
However, this results in the following encoded text:
<foo><![CDATA[
Testing 1 < 2
]]></foo>
I'm thinking that perhaps there might be a CDATA-specific libxml2 API. Or maybe I have to call something else to tell libxml2 not to automatically encode the node content?
Figured it out. The trick is in knowing that CDATA text content is actually a child and not a part of the current node, and the critical API to call is xmlNewCDataBlock(). Using the same example as above:
This will produce the following xml:
I cannot say for all versions of libxml2, but according to libxml2-2.9.4 the
doc
part of returning node ofxmlNewChild
comes from its parent. Also the parent of child node returned fromxmlNewCDataBlock
is set by doc parameter. So the following would be a good practice:The resulting xml is
And it would not matter if
node
is part of anxmlDoc
or not