how to write a CDATA node using libxml2?
Asked Answered
D

2

4

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?

Depolarize answered 12/4, 2011 at 9:10 Comment(0)
D
7

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>
Depolarize answered 12/4, 2011 at 20:1 Comment(5)
Stéphane What is the doc in the second line of the code. Is it a docptr. Is there a way to do without using docptr.Dixson
@Stephane xmlNewChild takes 3 parameters. not 4.Sheridansherie
@Sheridansherie Note that I wrote this in 2011. Lots of things have changed between 2011 and 2017!Stakeout
@Depolarize My bad! It does take 4 arguments.Sheridansherie
@KranthiKumar How about cdataPtr = xmlNewCDataBlock( parentPtr->doc, "Testing 1 < 2", 13 ); ?Tical
S
0

I cannot say for all versions of libxml2, but according to libxml2-2.9.4 the doc part of returning node of xmlNewChild comes from its parent. Also the parent of child node returned from xmlNewCDataBlock is set by doc parameter. So the following would be a good practice:

const char str[] = "said the kitty";
xmlNodePtr node = xmlNewNode(NULL, BAD_CAST "meow");
xmlNodePtr cdata_node = xmlNewCDataBlock(node->doc, BAD_CAST str, strlen(str));
xmlAddChild(node, cdata_node);

The resulting xml is

<meow><![CDATA[said the kitty]]></meow>

And it would not matter if node is part of an xmlDoc or not

Sheridansherie answered 22/2, 2017 at 1:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.