Find Key in XML with Boost

2019-09-21 02:30发布

问题:

I am using boost for the first time within an old code base that we have

iptree children = pt.get_child(fieldName);
for (const auto& kv : children) { 
    boost::property_tree::iptree subtree = (boost::property_tree::iptree) kv.second ;
//Recursive call
}

My problem is sometimes the fieldName doesn`t exist in the XML file and I have an exception

I tried :

boost::property_tree::iptree::assoc_iterator it = pt.find(fieldName);

but I dont know how to use the it I can`t use: if (it != null)

Any help please will be appreciated

I am using VS 2012

If it`s very complicated is there any other way to read a XML with nested nodes? I am working on that since 3 days

This is an Example of the XML

<?xml version="1.0" encoding="utf-8"?>
<nodeA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <nodeA.1>This is the Adresse</nodeA.1>
    <nodeA.2>
    <node1>
      <node1.1>
        <node1.1.1>Female</node1.1.1>
        <node1.1.2>23</node1.1.2>
        <node1.1.3>Engineer</node1.1.3>
      </node1.1>
      <node1.2>
        <node1.2.1>Female</node1.2.1>
        <node1.2.2>35</node1.2.2>
        <node1.2.3>Doctors</node1.2.3>
      </node1.2>
    </node1>
</nodeA.2>
<nodeA.3>Car 1</nodeA.3>
</nodeA>

回答1:

Use pt.get_child_optional(...) to prevent an exception. pt.find(...) returns an iterator which compares true to pt.not_found() on failure.

EDIT: How to use boost::optional<--->

boost::optional< iptree & > chl =  pt.get_child_optional(fieldname); 

    if(chl) { 
      for( auto a : *chl ) 
        std::cerr << ":" << a.first << ":" << std::endl; 
    } 


标签: c++ xml boost