我正在使用boostwrite_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时抛出以下异常错误。
在文档错误的元素内容中发现无效的XML字符(Unicode:0x0)
任何人都知道如何在使用boost属性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);
仔细检查后,XML中根本不支持NUL字节,句号(在XML中存储值Null(ASCII))。
要么去掉有问题的字节,要么使用某种编码,比如base64。
旧的分析和论证如下
请注意,属性树不是XML库,因此可能存在不符合XML标准的限制。
我仍然认为这是一个BUG,因为它不是往返的:属性树无法读回自己的序列化属性树:
生活在科里鲁
#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后端:在Coliru上直播