how to write a CDATA node using libxml2?

后端 未结 2 1917
忘掉有多难
忘掉有多难 2021-01-19 23:19

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, \"f         


        
相关标签:
2条回答
  • 2021-01-19 23:46

    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

    0 讨论(0)
  • 2021-01-19 23:59

    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>
    
    0 讨论(0)
提交回复
热议问题