c++xmlrapidxml

C++: How to extract a string from RapidXml


In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a std::string).
RapidXml has been recommended to me, but I can't see how to retrieve the XML back as a text string.
(I could iterate over the nodes and attributes and build it myself, but surely there's a build in function that I am missing.)


Solution

  • Althoug the documentation is poor on this topic, I managed to get some working code by looking at the source. Although it is missing the xml header which normally contains important information. Here is a small example program that does what you are looking for using rapidxml:

    #include <iostream>
    #include <sstream>
    #include "rapidxml/rapidxml.hpp"
    #include "rapidxml/rapidxml_print.hpp"
    
    int main(int argc, char* argv[]) {
        char xml[] = "<?xml version=\"1.0\" encoding=\"latin-1\"?>"
                     "<book>"
                     "</book>";
    
        //Parse the original document
        rapidxml::xml_document<> doc;
        doc.parse<0>(xml);
        std::cout << "Name of my first node is: " << doc.first_node()->name() << "\n";
    
        //Insert something
        rapidxml::xml_node<> *node = doc.allocate_node(rapidxml::node_element, "author", "John Doe");
        doc.first_node()->append_node(node);
    
        std::stringstream ss;
        ss <<*doc.first_node();
        std::string result_xml = ss.str();
        std::cout <<result_xml<<std::endl;
        return 0;
    }