Read/Write XML file with RapidXML

#include "rapidxml.hpp"
#include "rapidxml_print.hpp"
#include <fstream>
#include <sstream>

// Write xml file =================================
xml_document<> doc;
xml_node<>* decl = doc.allocate_node(node_declaration);
decl->append_attribute(doc.allocate_attribute("version", "1.0"));
decl->append_attribute(doc.allocate_attribute("encoding", "utf-8"));
doc.append_node(decl);

xml_node<>* root = doc.allocate_node(node_element, "rootnode");
root->append_attribute(doc.allocate_attribute("version", "1.0"));
root->append_attribute(doc.allocate_attribute("type", "example"));
doc.append_node(root);

xml_node<>* child = doc.allocate_node(node_element, "childnode");
root->append_node(child);

// Convert doc to string if needed
std::string xml_as_string;
rapidxml::print(std::back_inserter(xml_as_string), doc);

// Save to file
std::ofstream file_stored("file_stored.xml");
file_stored << doc;
file_stored.close();
doc.clear();

// Read xml file =================================
xml_document<> doc;
std::ifstream file("file_stored.xml");

std::stringstream buffer;
buffer << file.rdbuf();
std::string content(buffer.str());
doc.parse<0>(&content[0]);

2 thoughts on “Read/Write XML file with RapidXML

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s