3

我最近开始使用std::wstring而不是std::string避免非 ASCII 字符的奇怪结果,并且我没有找到一种方法来读取std::wstring使用 boost 库的路径类型为类型的 XML 文件。

我现在很安静地使用boost库。

我使用该boost::property_tree::read_xml函数boost::property_tree::wptree而不是通常的 ptree 结构。但遗憾的是,我无法将 astd::wstring作为第一个参数提供给 read_xml,这使得这一切变得更加困难。

我的问题是,是否有任何解决方法可以读取路径存储为的 XML 文件std::wstring

提前致谢!

4

2 回答 2

4

您可以使用 Boost Filesystem 支持的 Boost Iostreamsfile_descriptor_sink设备wpath

#include <boost/property_tree/xml_parser.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/filesystem.hpp>
#include <iostream>

namespace pt = boost::property_tree;
namespace io = boost::iostreams;
namespace fs = boost::filesystem;

int main()
{
    fs::wpath const fname = L"test.xml";
    io::file_descriptor_source fs(fname);
    io::stream<io::file_descriptor_source> fsstream(fs);

    pt::ptree xml;
    pt::read_xml(fsstream, xml);

    for (auto const& node : xml.get_child("root"))
        std::cout << node.first << ": " << node.second.get_value<std::string>() << "\n";
}

在 Coliru上查看它使用输入文件的地方:

<root>
    <child nodetype="element" with="attributes">monkey show</child>
    <child nodetype="element">monkey do</child>
</root>

并打印:

child: monkey show
child: monkey do
于 2014-08-29T21:59:13.013 回答
0

我找到了一个相当简单的可行解决方案,我所做的只是使用该方法std::wifstream的第一个参数boost::property_tree::read_xml

基本上三行代码:

boost::property_tree::wptree pt;
std::wifstream f(L"C:/äöå/file.xml");
boost::property_tree::read_xml(f, pt);
于 2014-08-29T21:58:50.483 回答