Using Boost to read and write XML files

前端 未结 15 2104
眼角桃花
眼角桃花 2020-11-28 02:37

Is there any good way (and a simple way too) using Boost to read and write XML files?

I can\'t seem to find any simple sample to read XML files using Boost. Can you

15条回答
  •  再見小時候
    2020-11-28 03:05

    
    
      
          4
          7
          9 
      
      
          454
          47
          29 
      
      
          String A
          String B  
        
    
    

    There is an easy way to read XML with BOOST. This example is with std::wstring:

    #include  
    #include 
    #include 
    #include 
    
    bool CMyClass::ReadXML(std::wstring &full_path)
    {
        using boost::property_tree::wptree;
    
        // Populate tree structure pt:
        wptree pt;
        std::wstringstream ss; ss << load_text_file(full_path); // See below for ref.
        read_xml(ss, pt);
    
        // Traverse pt:
        BOOST_FOREACH(wptree::value_type const& v, pt.get_child(L"Settings"))
        {
            if (v.first == L"GroupA")
            {
                unsigned int n1 = v.second.get(L"One");
                unsigned int n2 = v.second.get(L"Two");
                unsigned int n3= v.second.get(L"Three");
            }
            else if (v.first == L"GroupB")
            {
                std::wstring wstrA = v.second.get(L"A");
                std::wstring wstrB = v.second.get(L"B");
            }
        };
    }
    

    To read attributes is just a little bit more complicated.

    -

    Just for the reference:

    std::wstring load_text_file(std::wstring &full_path)
    {
        std::wifstream wif(full_path);
    
        wif.seekg(0, std::ios::end);
        buffer.resize(wif.tellg());
        wif.seekg(0);
        wif.read(buffer.data(), buffer.size());
    
        return buffer;
    }
    

提交回复
热议问题