如何使用libxml2编写CDATA节点? [英] how to write a CDATA node using libxml2?
问题描述
我正在使用libxml2读取/写入xml文件.现在,我正在尝试编写一个CDATA节点.
I'm using libxml2 to read/write xml files. Now I'm trying to write a CDATA node.
这是我尝试过的:
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>
我在想,也许可能存在特定于CDATA的libxml2 API.或者也许我不得不打电话告诉libxml2不要自动编码节点内容?
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?
推荐答案
弄清楚了.诀窍在于知道CDATA文本内容实际上是一个子元素,而不是当前节点的一部分,并且要调用的关键API是xmlNewCDataBlock().使用与上述相同的示例:
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 );
这将产生以下xml:
<foo><![CDATA[Testing 1 < 2]]></foo>
这篇关于如何使用libxml2编写CDATA节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!