Search code examples
c++xmlxml-attributeboost-propertytree

How to RESET attribute of xml element using boost::property_tree?


I have a xml file, I need to modify few attributes in that file.

My xml file is something like below:

<ns0:App xmlns:ns0="AppSchema" MyDir1="C:\App\Dir1" MyDir2="C:\App\Dir2"  ..... some other attributes>
    <ns0:Backend DisableBackend="false">
        <ns0:Logging EnableLogging="false" LogPath="c:\mylogs"/>
        <ns0:ExternalTool EnableTool="false"/>
    </ns0:Backend>
</ns0:App>

I need to modify values of attributes like MyDir1, MyDir2, EnableLogging, EnableTool in this xml file.

Googling helped me to get value from the attribute, but no luck in - how to modify attribute value or may be I am failing to use correct syntax.

Could anybody guide me in this ?

The code that I tried is as below:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
using namespace boost::property_tree;

int main()
{
    std::string xml_original = "C:\\temp\\config.xml";
    std::string xml_updated = "C:\\temp\\config_updated.xml";

    ptree tree;
    read_xml(sysCfg, tree);

    std::cout<<"old value: " << tree.get<std::string>("App.<xmlattr>.MyDir1");
    tree.put("App.<xmlattr>.MyDir1", "newPath");

    xml_writer_settings<char> w(' ', 4);
    write_xml(xml_updated, tree, std::locale(), w);
}

Solution

  • You have to include the namespace. I also used std::string for the xml_writer_settings:

    #include <boost/property_tree/ptree.hpp>
    #include <boost/property_tree/xml_parser.hpp>
    #include <iostream>
    
    using namespace boost::property_tree;
    
    int main()
    {
        std::string xml_original = "config.xml";
        std::string xml_updated = "config_updated.xml";
    
        ptree tree;
        read_xml(xml_original, tree);
    
        // must include the ns0 namespace
        std::cout << "old value: " << tree.get<std::string>("ns0:App.<xmlattr>.MyDir1");
        tree.put("ns0:App.<xmlattr>.MyDir1", "newPath");
    
        xml_writer_settings<std::string> w(' ', 4);
        write_xml(xml_updated, tree, std::locale(), w);
    }