我正在使用 boost write_xml
函数来创建 xml。我能够使用 Boost 创建成功的 xml。但是它在 xml 子元素的末尾添加了额外的 unicode 0x0 字符。
代码片段:
boost::property_tree::write_xml(oss, pt, boost::property_tree::xml_writer_make_settings<std::string>(' ', 4));
我将此 xml 发送到 Java 端应用程序,Java 在解析 boost 创建的 xml 时抛出以下异常错误。
An Invalid XML character(Unicode: 0x0) was found in the element content of the document error
任何人都知道如何在使用 boost property ptree
创建 xml 时从 XML 中删除 unicode 0x0 字符
。
最佳答案
您的数据嵌入了 NUL 字节。实现这一目标的一种方法:
std::string const hazard("erm\0", 4);
boost::property_tree::ptree pt;
pt.put("a.b.c.<xmlattr>.d", hazard);
更新
经过仔细检查,NUL 字节在 XML 中根本不支持,句号 ( Storing the value Null (ASCII) in XML)。
要么去掉有问题的字节,要么使用某种编码,比如 base64。
旧的分析和演示如下
请注意,Property Tree 不是 XML 库,因此可能存在不符合 XML 标准的限制。
我仍然认为这是一个 BUG,因为它没有往返:Property Tree cannot read its own serialized property tree back:
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>
int main() {
std::string const hazard("erm\0", 4);
{
std::ofstream ofs("NULbyte.xml");
boost::property_tree::ptree pt;
pt.put("a.b.c.<xmlattr>.d", hazard);
write_xml(ofs, pt);
}
{
std::ifstream ifs("NULbyte.xml");
boost::property_tree::ptree pt;
read_xml(ifs, pt);
std::cout << (hazard == pt.get<std::string>("a.b.c.<xmlattr>.d")) << "\n";
}
}
如果需要,您可以正确使用 JSON 后端: Live On Coliru
关于c++ - boost 属性 ptree : boost write_xml adding unicode 0x0 character in child element in xml file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47071608/