Search code examples
c++eclipse-cdtrapidxml

RapidXml: Selecting a first_attribute value


I am a starter in RapidXml.

<catalog>
   <book id="bk101" value="ABCDEFGHIJKLMNOPQRSTUVWXYZ">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102" value="ABCDEFGHIJKLMNOPQRSTUVWXYZ">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, a

nd her own childhood to become queen 
      of the world.</description>
   </book>
</catalog>

For this XML how can I select only when id="bk102" and then parse value="ABCDEFGHIJKLMNOPQRSTUVWXYZ"?

Thanks all in advance!


Solution

  • The solution is quite straightforward:

    #include <cstddef>
    #include <cstring>
    #include <iostream>
    
    #include "rapidxml.hpp"
    #include "rapidxml_utils.hpp"
    
    …
    
    rapidxml::file<> xml_file("/path/to/xml/file");
    rapidxml::xml_document<> xml_doc;
    xml_doc.parse<0>(xml_file.data());
    
    const rapidxml::xml_node<> *catalog_node = xml_doc.first_node("catalog");
    if (catalog_node == NULL) {
        std::cout << "No \"catalog\" node!" << std::endl;
        return;
    }
    
    for (const rapidxml::xml_node<> *book_node = catalog_node->first_node("book");
        book_node != NULL;
        book_node = book_node->next_sibling()) {
    
        const rapidxml::xml_attribute<> *id_attribute = book_node->first_attribute("id");
        if (id_attribute == NULL || strcmp(id_attribute->value(), "bk102") != 0) {
            continue;
        }
    
        const rapidxml::xml_attribute<> *value_attribute = book_node->first_attribute("value");
        if (value_attribute == NULL) {
            continue;
        }
    
        std::cout << "Found \"value\" attribute with value: " << value_attribute->value() << std::endl;
    }