c++ - 使用 boost::property_tree 写入 CDATA XML 节点

标签 c++ xml boost cdata boost-propertytree

我正在尝试使用 boost::property_tree 编写包含 CDATA 节点的 XML 文件。但是,由于诸如<之类的字符, > , &等在写入 XML 文件时会自动转义,例如

xml.put("node", "<![CDATA[message]]>")

将显示为

<node>&lt![CDATA[message]]&gt</node> 

在 XML 文件中。有没有办法使用 property_tree 正确编写 CDATA 节点,或者这只是库的限制?

最佳答案

Boost documentation明确表示它无法区分 CDATA 和非 CDATA 值:

The XML storage encoding does not round-trip perfectly. A read-write cycle loses trimmed whitespace, low-level formatting information, and the distinction between normal data and CDATA nodes. Comments are only preserved when enabled. A write-read cycle loses trimmed whitespace; that is, if the origin tree has string data that starts or ends with whitespace, that whitespace is lost.

我几次遇到同样的问题都是在非常具体的情况下,我知道不需要其他转义数据,因此对生成的文件进行简单的后处理替换转义字符就足够了。

作为一般示例:

std::ostringstream ss;
pt::write_xml(ss, xml, pt::xml_writer_make_settings<std::string>('\t', 1));

auto cleaned_xml = boost::replace_all_copy(ss.str(), "&gt;", ">");
cleaned_xml = boost::replace_all_copy(cleaned_xml, "&lt;", "<");
cleaned_xml = boost::replace_all_copy(cleaned_xml, "&amp;", "&"); // last one

std::ofstream fo(path);
fo << cleaned_xml;

更详细的解决方案应包括查找开头 <![CDATA[ 和结尾 ]]>,并仅在这些限制内进行替换,以避免替换正确转义的符号.

this answer 中提出了另一个解决方案但我从来没用过。

关于c++ - 使用 boost::property_tree 写入 CDATA XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54038989/

相关文章:

c++ - 如何禁用#pragma 警告?

java - 在 java 中禁用唯一分区属性模式验证

javascript - 准备要远程加载的 SQLite 数据库以进行移动开发

c++ - lambda 在 boost spirit 的惰性参数中不被接受

c++ - 同一 boost tcp 套接字对象上的多个连接

c++ - FCam - 弱光/HDR 照片

C++ 类构造函数抛出异常

c++ - 如何使用 boost::process 向子进程发送 SIGTERM

c++ - Clang 编译器使用运算符 T* 构造对象时出错

java - 在 xml 解析中查看 android 的 flipper 示例