【问题标题】:Boost Property ptree: boost write_xml adding unicode 0x0 character in child element in xml fileBoost Property ptree:boost write_xml 在 xml 文件的子元素中添加 unicode 0x0 字符
【发布时间】:2018-04-14 18:13:29
【问题描述】:

我正在使用 boost write_xml 函数来创建 xml。我能够使用 Boost 创建成功的 xml。但它在 xml 子元素的末尾添加了额外的 unicode 0x0 字符。

代码sn-p:

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 character

【问题讨论】:

  • 这对我来说是新的,为什么 write_xml 会写一个 0x0 代码点?可能 your 原始属性树实例在写入 xml 之前包含 0 个字符? (property_tree 使用 std::basic_string 反过来可以存储 0 个字符)请发布MCVE

标签: c++ xml boost unicode boost-propertytree


【解决方案1】:

您的数据已嵌入 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 无法读取其自己的序列化属性树:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-10
    • 2017-10-07
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2016-08-10
    • 2013-01-17
    相关资源
    最近更新 更多