2016-03-08 39 views
0

我是RapidXml的入門者。RapidXml:選擇first_attribute值

<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> 

對於這個XML我怎麼只能選擇當id="bk102",然後解析value="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

非常感謝!

回答

1

解決的辦法很簡單:

#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; 
} 
+1

很多很多的感謝謝爾蓋。它的工作很棒! :) – Shahparan

+0

@Shahparan,這沒什麼!很高興幫助。 –