c++ - boost 属性 ptree : boost write_xml adding unicode 0x0 character in child element in xml file

标签 c++ xml boost unicode boost-propertytree

我正在使用 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:

Live On Coliru

#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/

相关文章:

php - 如何在大的 xml 文件中使用 php?

c++ - boost::geometry 和 std 命名空间与 Visual Studio 2013 冲突

c++ - 在 boost::thread 线程中使用异常

sql-server - 使用 XML 字符串更新表中的数据

c++ - 重载运算符返回什么类型的值(对于用户定义类型): rvalue or lvalue?

c++ - 写入WAV文件时定期创建静音

c++ - 分配 vector 的前缀和并将结果存储在静态 vector 中

xml - 根据数组中数据的匹配更新 XML 文件的特定节点

elasticsearch - 如果搜索查询包含弹性的特定术语/文本,如何 boost 某些文档

c++ - Thread.joinable 返回 true 即使线程还没有完成执行