如何使用libxml2编写CDATA节点? [英] how to write a CDATA node using libxml2?

查看:199
本文介绍了如何使用libxml2编写CDATA节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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>&lt;![CDATA[
Testing 1 &lt; 2
]]&gt;</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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆