1

Is there any way of XPATH usage in boost similar to C# (SelectSingleNode() etc).

I am trying with boost::property_tree::ptree, but it is bit different than C#/VBA XML parsing.

<?xml version="1.0"?>
<Classes>

  <Class name="first">
   <Elements>
    <ElementA>aa</ElementA>
    <ElementB>bb</ElementB>
   </Elements>
  </Class>

  <Class name="second">
   <Elements>
    <ElementA>cc</ElementA>
    <ElementB>dd</ElementB>
   </Elements>
  </Class>

  <Class name="third">
   <Elements>
    <ElementA>ee</ElementA>
    <ElementB>ff</ElementB>
   </Elements>
  </Class>

</Classes>

I have to iterate on this kind of config and select subtree on the basis of Classes/Class[@name] attribute.

How can I do this with ptree.

1 Answers1

0

Got few good links to understand the data structure of ptree and from there it is easy.

Started from here , Boost property tree : how to get child of child tree with a xml file

then here, https://akrzemi1.wordpress.com/2011/07/13/parsing-xml-with-boost/

#include <iostream>
#include <string>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <fstream>

int main()
{
  std::string xml = R"(<?xml version="1.0"?>
<Classes>

  <Class name="first">
   <Elements>
    <ElementA>aa</ElementA>
    <ElementB>bb</ElementB>
   </Elements>
  </Class>

  <Class name="second">
   <Elements>
    <ElementA>cc</ElementA>
    <ElementB>dd</ElementB>
   </Elements>
  </Class>

  <Class name="third">
   <Elements>
    <ElementA>ee</ElementA>
    <ElementB>ff</ElementB>
   </Elements>
  </Class>

</Classes>)";

  //std::cout << xml;

  using boost::property_tree::ptree;
  std::stringstream ss(xml);
  ptree p;
  read_xml(ss,p);

  std::ostringstream subTree;
  BOOST_FOREACH( ptree::value_type const& v, p.get_child("Classes") )
  {   
      //if(v.second.get<std::string>("<xmlattr>.name") ==  "first") 
       write_xml(subTree, v.second);
       std::cout << subTree.str();
       std::cout << "\n====================\n";

  }
}
  • this one is also good for knowledge, https://stackoverflow.com/questions/28372268/getting-the-ptree-from-boostproperty-treeptreeiterator – pawan kataria Apr 15 '19 at 17:56