Search code examples
c++boostboost-propertytree

xml parsing in boost with property tree


I have following xml file. It is showing firmware version info for 2 drives, bay 1 and bay 2. At this point, everything looks similar for both drives, except bay 1 and bay 2. But I expect these to have different firmware version. I need to read and be able to compare if bay 1 and bay 2 drives has same firmware versions. I am using Boost(version 1.41 property tree on Red Hat and C++)

<Node>
   <Type>XET</Type>
   <Reference>00110232</Reference>
   <Date>02-09-2012</Date>
</Node>
<Node>
   <Type>XET</Type>
   <Reference>000000</Reference>
   <Date>02-09-2012</Date>
</Node>

My C++ isnt all that great and documentation on Boost really sucks. So far I can read the xml file but I can not search and see if firmware versions are same. I tried couple of different things without much luck. I would really appreciate some help with this.

  #include <boost/property_tree/ptree.hpp>
  #include <boost/property_tree/xml_parser.hpp>


  using boost::property_tree::ptree;
  ptree pt;

  // reading file.xml
  read_xml(xmlFilePath, pt, boost::property_tree::xml_parser::trim_whitespace );

  string c ;
  try
  {
    c = pt.get<string>("Node.Reference");
  }
  catch(std::exception const& e)
  {
    std::cout << e.what() << std::endl;
  }

  cout << "value is: " << c << endl;

I got some of my issues solved. Can someone please tell me how to get all nodes? This code currently finds the 1st match and print it, nothing else. If I knew how many nodes are going to be there, I could have used a for loop. Anyone else have a better idea, like using an iterator? If so please show me how to do that.


Solution

  • ...
    #include <boost/foreach.hpp>
    ...
    
    namespace PT = boost::property_tree;
    
    
    ...
        read_xml(xmlFilePath, pt, boost::property_tree::xml_parser::trim_whitespace );
    
        BOOST_FOREACH(const PT::ptree::value_type& node, pt.get_child("Node"))
        {
            PT::ptree& nodeTree = node.second;
            const std::string type      = nodeTree.get<std::string>("Type");
            const std::string reference = nodeTree.get<std::string>("Reference");
            const std::string date      = nodeTree.get<std::string>("Date");
            ...
        }
    ...