3
#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;
}

This program prints OK and writes XML file as expected:

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

Now I replace s value with non-ASCII characters:

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

When the program is executed, it prints: write error, and XML file looks like this:

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

How can I fix this? I need to write non-ASCII data to XML file, using Boost property tree.

Alex F
  • 42,307
  • 41
  • 144
  • 212

2 Answers2

1

Using Boost 1.55 and VS2012 I ended up writing as below and get valid unicode characters out:

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);
0

I think you shouldn't use std::locale() but utf8 locale. In boost-1.51, you can use boost/detail/utf8_codecvt_facet.ipp to make utf8 locale.

First, include utf8_codecvt_facet.ipp like this:

#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

And then, make utf8 locale and write xml with the locale.

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

It works fine in my environment.

H. Tsubota
  • 91
  • 6