How to get attribute value in RapidXML

Problem:

You have a rapidxml::xml_node instance for which you want to access a specific attribute,  e.g. my-attribute

Solution

Use first_attribute with the name argument set to a string:

rapidxml::xml_attribute<>* attr = node->first_attribute("my-attribute");

Remember that first_attribute() returns nullptr if no such attribute exists so be sure to check for that to avoid segmentation faults!

Full example:

XML:

<?xml version="1.0" encoding="UTF-8"?>
<root-element>
    <child my-attr="foo"></child>
</root-element>

C++:

#include <rapidxml/rapidxml_utils.hpp>
#include <string>
#include <iostream> 

using namespace rapidxml;
using namespace std;

int main() {
    rapidxml::file<> xmlFile("test.xml");
    // Create & parse document
    rapidxml::xml_document<> doc;
    doc.parse<0>(xmlFile.data());
    
    // Get root node
    rapidxml::xml_node<> *root = doc.first_node("root-element");
    rapidxml::xml_node<> *child = root->first_node("child");

    // Get & print attribute
    rapidxml::xml_attribute<>* attr = child->first_attribute("my-attr");
    if(attr == nullptr) {
        cout << "No such attribute!" << endl;
    } else {
        cout << attr->value() << endl;
    }
}

Or you can use this snippet function to get either the attribute value or a default value:

#include <rapidxml/rapidxml_utils.hpp>
#include <string>
#include <iostream> 

using namespace rapidxml;
using namespace std;

/**
 * Return either the ->value() of attr or default_value if attr == nullptr
 */
inline string attr_value_or_default(rapidxml::xml_attribute<>* attr, string default_value="") {
    if(attr == nullptr) {
        return default_value;
    } else {
        return attr->value();
    }
}

int main() {
    rapidxml::file<> xmlFile("test.xml");
    // Create & parse document
    rapidxml::xml_document<> doc;
    doc.parse<0>(xmlFile.data());
    
    // Get root node
    rapidxml::xml_node<> *root = doc.first_node("root-element");
    rapidxml::xml_node<> *child = root->first_node("child");

    // Get & print attribute+
    rapidxml::xml_attribute<>* attr = child->first_attribute("my-attr");
    cout << attr_value_or_default(attr, "No such attribute!") << endl;
}