[英]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文件:
<?xml version="1.0" encoding="utf-8"?>
<Data>
<Name>Alex</Name>
</Data>
Now I replace s
value with non-ASCII characters: 现在我用非ASCII字符替换
s
值:
//wstring s(L"Alex");
wstring s(L"Алекс");
When the program is executed, it prints: write error
, and XML file looks like this: 执行程序时,会打印:
write error
,XML文件如下所示:
<?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.
我需要使用Boost属性树将非ASCII数据写入XML文件。
I think you shouldn't use std::locale() but utf8 locale . 我认为你不应该使用std :: locale()而是使用utf8语言环境 。 In boost-1.51, you can use boost/detail/utf8_codecvt_facet.ipp to make utf8 locale.
在boost-1.51中,您可以使用boost / detail / utf8_codecvt_facet.ipp来制作utf8语言环境。
First, include utf8_codecvt_facet.ipp like this: 首先,像这样包括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
And then, make utf8 locale and write xml with the locale. 然后,创建utf8语言环境并使用语言环境编写xml。
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. 它在我的环境中工作正常。
Using Boost 1.55 and VS2012 I ended up writing as below and get valid unicode characters out: 使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.