提高写入错误的编码

问题描述 投票:1回答:2

我想写一个提升wptree到一个文件。使用我的Windows上的当前std::locale,设置为C输出xml文件的某些部分如下所示:

<demo>
    <demostring1>Abc</demostring1>
    <demostring2>abc&gt;def</demostring2>
</demo>

但我希望输出看起来像这样:

<demo>
    <demostring1>Abc</demostring1>
    <demostring2>abc>def</demostring2>
</demo>

这是将wptree写入文件的代码:

boost::property_tree::xml_parser::write_xml(wstringToString(filename), mainTree,
    std::locale(),
    boost::property_tree::xml_writer_make_settings<std::wstring>(' ', 4));

我尝试通过改变语言环境

boost::property_tree::xml_parser::write_xml(wstringToString(filename), mainTree,
    std::locale("en_US.UTF-8"), // Give an Exception on runtime.
    boost::property_tree::xml_writer_make_settings<std::wstring>(' ', 4));

如何更改区域设置以便在XML文件中正确打印符号?

c++ xml boost
2个回答
1
投票

但我希望输出看起来像这样:

所以你想拥有无效的XML。 https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharData

除了Boost没有真正拥有XML库这一事实之外,您将找不到一个可以完成您所描述内容的非破坏XML库。

如果你坚持,你将不得不手动连接字符串。


0
投票

你需要把你的文字与标记

ABC> DEF

进入CDATA部分,以使解析器能够解析这样的XML。

如果您有C ++ 11,您可以尝试使用我的库而不是boost属性树。您可以在以下位置找到库:https://github.com/incoder1/IO

您案例的示例如下:

#include <iostream>
#include <files.hpp>
#include <stream.hpp>
#include <xml_types.hpp>

static const char* PROLOGUE = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";

static io::s_write_channel create_file_channel(const char* path) {
    io::file f( path );
    std::error_code ec;
    io::s_write_channel ret = f.open_for_write(ec, io::write_open_mode::overwrite);
    io::check_error_code(ec);
    return ret;
}

// demo structure we will write into XML
struct demo
{
    std::string demostring_1;
    std::string demostring_2;
};

// A C++ meta-programming datatype to define the XML file format
typedef io::xml::complex_type< demo,
    std::tuple<>, // this one is for XML attributes
// two embedded tags
    std::tuple<io::xml::string_element,
            io::xml::string_element> > demo_xml_type;

// this one opens file for writing, can be changed to std::fostream
static demo_xml_type to_xml_type(const demo& obj) {
    io::xml::string_element demostring_1_el("demostring1", obj.demostring_1);
    io::xml::string_element demostring_2_el("demostring2", obj.demostring_2);
    return demo_xml_type("demo", std::tuple<>(), std::make_tuple(demostring_1_el, demostring_2_el ) );
}

int main()
{
    io::channel_ostream<char> xml( create_file_channel("demo.xml"));
    xml << PROLOGUE;
    // make an object to serialize into XML 
    demo obj = {"Abc","<![CDATA[abc>def]]>"};
    // Map structure to XML format
    demo_xml_type xt = to_xml_type(obj);
    // writes structure into XM file
    xt.marshal(xml,1);
    // write same XML into console
    std::cout << PROLOGUE << std::endl;
    xt.marshal(std::cout,1);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.