我想在文件中写一个提升wptree
。
使用我的Windows上的当前std::locale
,设置为C
输出xml文件的某些部分如下所示:
<demo>
<demostring1>Abc</demostring1>
<demostring2>abc>def</demostring2>
</demo>
但我希望输出看起来像这样:
<demo>
<demostring1>Abc</demostring1>
<demostring2>abc>def</demostring2>
</demo>
这是将wptree
写入文件的代码:
boost::property_tree::xml_parser::write_xml(wstringToString(filename), mainTree,
std::locale(),
boost::property_tree::xml_writer_make_settings<std::wstring>(' ', 4));
我尝试通过
更改语言环境boost::property_tree::xml_parser::write_xml(wstringToString(filename), mainTree,
std::locale("en_US.UTF-8"), // Give an Exception on runtime.
boost::property_tree::xml_writer_make_settings<std::wstring>(' ', 4));
如何更改区域设置以便在XML文件中正确打印符号?
答案 0 :(得分:1)
但我希望输出看起来像这样:
所以你想拥有无效的XML。 https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharData
除了Boost没有真正拥有XML库的事实之外,你找不到一个可以完成你所描述的非破坏的XML库。
如果你坚持,你必须手动连接字符串。
答案 1 :(得分:0)
你需要把你的文字加上标记
ABC&GT; DEF
进入CDATA部分,以使解析器能够解析这样的XML。
如果你有C ++ 11,你可以尝试使用我的库而不是boost属性树。你可以在https://github.com/incoder1/IO找到库
您案例的示例如下:
#include <iostream>
#include <files.hpp>
#include <stream.hpp>
#include <xml_types.hpp>
static const char* PROLOGUE = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
static io::s_write_channel create_file_channel(const char* path) {
io::file f( path );
std::error_code ec;
io::s_write_channel ret = f.open_for_write(ec, io::write_open_mode::overwrite);
io::check_error_code(ec);
return ret;
}
// demo structure we will write into XML
struct demo
{
std::string demostring_1;
std::string demostring_2;
};
// A C++ meta-programming datatype to define the XML file format
typedef io::xml::complex_type< demo,
std::tuple<>, // this one is for XML attributes
// two embedded tags
std::tuple<io::xml::string_element,
io::xml::string_element> > demo_xml_type;
// this one opens file for writing, can be changed to std::fostream
static demo_xml_type to_xml_type(const demo& obj) {
io::xml::string_element demostring_1_el("demostring1", obj.demostring_1);
io::xml::string_element demostring_2_el("demostring2", obj.demostring_2);
return demo_xml_type("demo", std::tuple<>(), std::make_tuple(demostring_1_el, demostring_2_el ) );
}
int main()
{
io::channel_ostream<char> xml( create_file_channel("demo.xml"));
xml << PROLOGUE;
// make an object to serialize into XML
demo obj = {"Abc","<![CDATA[abc>def]]>"};
// Map structure to XML format
demo_xml_type xt = to_xml_type(obj);
// writes structure into XM file
xt.marshal(xml,1);
// write same XML into console
std::cout << PROLOGUE << std::endl;
xt.marshal(std::cout,1);
return 0;
}