Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Unicode string to XML with Boost Property Tree

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

like image 874
Alex F Avatar asked Jan 25 '26 00:01

Alex F


1 Answers

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);
like image 96
jmenninkainen Avatar answered Jan 27 '26 15:01

jmenninkainen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!