Search code examples
libxml2cdata

how to write a CDATA node using libxml2?


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>&lt;![CDATA[
Testing 1 &lt; 2
]]&gt;</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?


Solution

  • 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:

    nodePtr = xmlNewChild( parentPtr, NULL, "foo", NULL );
    cdataPtr = xmlNewCDataBlock( doc, "Testing 1 < 2", 13 );
    xmlAddChild( nodePtr, cdataPtr );
    

    This will produce the following xml:

    <foo><![CDATA[Testing 1 < 2]]></foo>