我正在尝试使用 boost::property_tree 编写包含 CDATA 节点的 XML 文件。但是,由于诸如<
之类的字符, >
, &
等在写入 XML 文件时会自动转义,例如
xml.put("node", "<![CDATA[message]]>")
将显示为
<node><![CDATA[message]]></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(), ">", ">");
cleaned_xml = boost::replace_all_copy(cleaned_xml, "<", "<");
cleaned_xml = boost::replace_all_copy(cleaned_xml, "&", "&"); // 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/