Pregunta

I'd like to read from XML to C++ using RapidXML. However, if a node doen't exist or a value is missing the program crashes.

for (rapidxml::xml_node<> * xmlasset_node = root_node->first_node("Asset"); xmlasset_node; xmlasset_node = xmlasset_node->next_sibling())
{mystring += xmlasset_node->first_attribute("name")->value()};

However, this "name" attribute doesn't exist in all nodes and is to be filled with a default value, if its not in XML. Similar to this, I've got some sub-nodes not in all nodes. The reason is just to keep the XML as small and clear as possible for manual adjustments.

How can a check/test be implemented (C++), to prevent the program from crashing and just taking default values if a value/node doesn't exist?

Kind regards, - Corak

¿Fue útil?

Solución

Here is what I do, you can compare if the value of the node and its attribute matches your criteria then you accepts it: // basically I am looking for "settings" node then "network" subnode, then "port" attribute

  if( boost::iequals(doc.first_node()->next_sibling()->name(), "settings"))
        {
            for (xml_node<> *node = doc.first_node()->next_sibling()->first_node(); node; node = node->next_sibling())
            {

                // find network tag 
                if (boost::iequals(node->name(),"network"))
                {

                    for (xml_attribute<> *attr = node->first_attribute(); attr; attr = attr->next_attribute())
                    {
                        if ( boost::iequals(attr->name(), "port"))
                        {
                            strcpy(attr->value(), portname);
                        }
                    }
                }
          }
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top