c++ - 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 , writes xml file expected:
<?xml version="1.0" encoding="utf-8"?> <data> <name>alex</name> </data>
now replace s
value non-ascii characters:
//wstring s(l"alex"); wstring s(l"Алекс");
when program executed, prints: write error
, , xml file looks this:
<?xml version="1.0" encoding="utf-8"?> <data> <name>
how can fix this? need write non-ascii data xml file, using boost property tree.
i think shouldn't use std::locale() utf8 locale. in boost-1.51, can use boost/detail/utf8_codecvt_facet.ipp make utf8 locale.
first, include utf8_codecvt_facet.ipp 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 , write xml 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 environment.
Comments
Post a Comment