【问题标题】:Writing Unicode string to XML with Boost Property Tree使用 Boost 属性树将 Unicode 字符串写入 XML
【发布时间】:2014-03-06 09:22:20
【问题描述】:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>

using namespace std;

int main()
{
    wstring s(L"Alex");

    boost::property_tree::wptree mainTree;
    boost::property_tree::wptree dataTree;

    dataTree.put(L"Name", s);
    mainTree.add_child(L"Data", dataTree);
    boost::property_tree::xml_writer_settings<wchar_t> w(L' ', 3);

    try
    {
        write_xml("Data.xml", mainTree, std::locale(), w);
    }
    catch(boost::property_tree::xml_parser_error& error)
    {
        cout << error.message().c_str() << endl;
        return 1;
    }

    cout << "OK" << endl;
    return 0;
}

这个程序打印OK并按预期写入XML文件:

<?xml version="1.0" encoding="utf-8"?>
<Data>
   <Name>Alex</Name>
</Data>

现在我用非 ASCII 字符替换 s 值:

    //wstring s(L"Alex");
   wstring s(L"Алекс");

程序执行时打印:write error,XML文件如下:

<?xml version="1.0" encoding="utf-8"?>
<Data>
   <Name>

我该如何解决这个问题?我需要使用 Boost 属性树将非 ASCII 数据写入 XML 文件。

【问题讨论】:

    标签: c++ xml boost boost-propertytree


    【解决方案1】:

    使用 Boost 1.55 和 VS2012 我最终编写如下并得到有效的 unicode 字符:

    auto settings = xml_writer_make_settings<wchar_t>(L' ', 2, L"utf-8");
    std::locale utf8bom(std::locale(), new std::codecvt_utf8<wchar_t, 0x10ffff, std::generate_header>);
    write_xml(strFileName, xmlTree, utf8bom, settings);
    

    【讨论】:

      【解决方案2】:

      我认为你不应该使用 std::locale() 而是 utf8 语言环境。在 boost-1.51 中,您可以使用 boost/detail/utf8_codecvt_facet.ipp 来制作 utf8 语言环境。

      首先,像这样包含 utf8_codecvt_facet.ipp:

      #define BOOST_UTF8_BEGIN_NAMESPACE \
      namespace boost { namespace detail {
      #define BOOST_UTF8_DECL
      #define BOOST_UTF8_END_NAMESPACE }}
      #include <boost/detail/utf8_codecvt_facet.ipp>
      #undef BOOST_UTF8_END_NAMESPACE
      #undef BOOST_UTF8_DECL
      #undef BOOST_UTF8_BEGIN_NAMESPACE
      

      然后,制作 utf8 语言环境并使用该语言环境编写 xml。

      std::locale utf8_locale(std::locale(), new boost::detail::utf8_codecvt_facet);
      write_xml("Data.xml", mainTree, utf8_locale, w);
      

      它在我的环境中运行良好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-18
        • 1970-01-01
        • 1970-01-01
        • 2019-09-04
        • 1970-01-01
        • 2018-11-20
        • 2020-02-02
        • 1970-01-01
        相关资源
        最近更新 更多