C++:
Working with XML

How to:

Here’s a simple way to parse XML using the TinyXML-2 library:

#include <tinyxml2.h>
#include <iostream>

int main() {
    tinyxml2::XMLDocument doc;
    doc.Parse("<root><message>Hello, World!</message></root>");
    const char* content = doc.FirstChildElement("root")->FirstChildElement("message")->GetText();
    std::cout << content << std::endl;
    return 0;
}

Sample output:

Hello, World!

And this is how you create an XML file:

#include <tinyxml2.h>
#include <iostream>

int main() {
    tinyxml2::XMLDocument doc;
    auto* declaration = doc.NewDeclaration();
    doc.InsertFirstChild(declaration);
    auto* root = doc.NewElement("root");
    doc.InsertEndChild(root);
    auto* message = doc.NewElement("message");
    message->SetText("Hello, World!");
    root->InsertEndChild(message);
    doc.SaveFile("output.xml");
    return 0;
}

This generates an XML file output.xml with contents:

<?xml version="1.0"?>
<root>
    <message>Hello, World!</message>
</root>

Deep Dive

XML has been pivotal in web services and data storage since the late ’90s. While JSON and YAML are now more common for config and interop, XML is still huge in many enterprise systems. Parsing XML in C++ can feel old-school with manual DOM/SAX parsing. Thankfully, libraries like TinyXML-2 simplify it. C++ has no built-in XML support; libraries like TinyXML-2, pugixml, or Xerces wrap up the tough bits.

See Also