Attributwert in RapidXML abrufen

English Deutsch

Problem:

Du hast eine rapidxml::xml_node-Instanz, für die du auf ein bestimmtes Attribut zugreifen möchtest, z.B. my-attribute

Lösung

Verwende first_attribute mit dem name-Argument, das auf einen String gesetzt ist:

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

Denke daran, dass first_attribute() nullptr zurückgibt, wenn kein solches Attribut existiert, also stelle sicher, dass du dies überprüfst, um Segmentation Faults zu vermeiden!

Vollständiges Beispiel:

XML:

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

C++:

rapidxml-example.cpp
#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;
    }
}

Oder du kannst diese Snippet-Funktion verwenden, um entweder den Attributwert oder einen Standardwert zu erhalten:

rapidxml-helpers.cpp
#include <rapidxml/rapidxml_utils.hpp>
#include <string>
#include <iostream>

using namespace rapidxml;
using namespace std;

/**
 * Gibt entweder den ->value() von attr oder default_value zurück, wenn 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;
}

Check out similar posts by category: C/C++