Search code examples
c++xmlboostwstringwidestring

Boost library, using std::wstring as filename with boost::property_tree::read_xml


I recently started using std::wstring instead of std::string to avoid weird results with non-ASCII characters, and I didn't find a way to read an XML file where the path is of type std::wstring using the boost library.

I'm using the boost library quiet a lot nowadays.

I use the boost::property_tree::read_xml function with boost::property_tree::wptree instead of the usual ptree struct. But sadly I cannot feed a std::wstring as the first parameter to read_xml which makes it all harder.

My question is, are there any work around for reading a XML file where the path is storted as a std::wstring?

Thanks in advance!


Solution

  • You could use the Boost Iostreams file_descriptor_sink device which supports wpath from Boost Filesystem:

    #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";
    }
    

    See it Live On Coliru where it uses the input file:

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

    and prints:

    child: monkey show
    child: monkey do