TinyXML2: A C++ Library for XML Processing

To work with TinyXML2 in your C++ projects, you'll need to include tinyxml2.h and tinyxml2.cpp in your project. The xmltest.cpp file serves as an official example and learning resource. The library is open source and available at the GitHub repository.

For compilation, you can use the following command:

g++ -g -std=c++17 -LD:\workspace\C++\XMLFileModifier main.cpp tinyxml2.cpp -o test

The -g flag generates debugging information, which is useful for debugging but increases the executable file size. The -L flag specifies the library search path where the TinyXML2 header files are located.

Common Operations

Creating XML Documents

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

using namespace tinyxml2;

int main() {
    // Initialize XML document
    XMLDocument xmlDocument;

    // Add XML declaration
    XMLDeclaration* declaration = xmlDocument.NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\"");
    xmlDocument.InsertFirstChild(declaration);

    // Create root element
    XMLElement* rootElement = xmlDocument.NewElement("root");
    xmlDocument.InsertEndChild(rootElement);

    // Create first person element
    XMLElement* firstPerson = xmlDocument.NewElement("person");
    rootElement->InsertEndChild(firstPerson);
    firstPerson->SetAttribute("name", "John");
    XMLText* textContent = xmlDocument.NewText("This is some text.");
    firstPerson->InsertEndChild(textContent);

    // Create second person element
    XMLElement* secondPerson = xmlDocument.NewElement("person");
    rootElement->InsertEndChild(secondPerson);
    secondPerson->SetAttribute("name", "anna");

    // Create child element for second person
    XMLElement* childElement = xmlDocument.NewElement("sonPerson");
    secondPerson->InsertEndChild(childElement);
    childElement->SetAttribute("name", "2333");
    XMLText* childText = xmlDocument.NewText("51555");
    childElement->InsertEndChild(childText);

    // Save XML document to file
    xmlDocument.SaveFile("example.xml");

    std::cout << "XML document created and saved to 'example.xml'" << std::endl;

    return 0;
}

The generated XML file will look like this:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <person name="John">This is some text.</person>
    <person name="anna">
        <sonPerson name="2333">51555</sonPerson>
    </person>
</root>

Reading and Modifying XML Files

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

using namespace tinyxml2;

int main() {
    // Create XML document
    XMLDocument xmlDocument;

    // Load XML file
    XMLError loadResult = xmlDocument.LoadFile("D:\\Temp\\WorkSpace\\C++\\example.xml");
    
    // Check if loading was successful
    if (loadResult == XML_SUCCESS) {
        std::cout << "XML document loaded successfully." << std::endl;
    } else {
        std::cout << "Failed to load XML document. Error code: " << loadResult << std::endl;
        return -1;
    }

    // Get root element
    XMLElement* rootElement = xmlDocument.FirstChildElement("root");
    if (!rootElement) {
        std::cout << "Root element 'root' not found in the XML document." << std::endl;
        return -1;
    }

    // Iterate through person elements
    for (XMLElement* personElement = rootElement->FirstChildElement("person"); 
         personElement; 
         personElement = personElement->NextSiblingElement("person")) {
        const char* name = personElement->Attribute("name");
        const char* text = personElement->GetText();

        if (name) {
            std::cout << "Name: " << name << std::endl;
        }

        if (text) {
            std::cout << "Text: " << text << std::endl;
        }
        
        // Modify attributes and text
        personElement->SetAttribute("name", "xiaoming");
        personElement->SetText("100010111010100");
    }
    
    // Save modified document
    xmlDocument.SaveFile("examples.xml");

    return 0;
}

Reading Unknown XML Files

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

using namespace tinyxml2;

int main() {
    // Create XML document
    XMLDocument xmlDocument;

    // Load XML file
    XMLError loadResult = xmlDocument.LoadFile("D:\\Temp\\WorkSpace\\C++\\example.xml");

    // Check if loading was successful
    if (loadResult != XML_SUCCESS) {
        return -1;
    }

    // Get root element
    XMLElement* rootElement = xmlDocument.RootElement();

    if (rootElement) {
        // Traverse the entire XML structure
        for (XMLElement* element = rootElement->FirstChildElement(); 
             element; 
             element = element->NextSiblingElement()) {
            // Get element name
            const char* elementName = element->Name();
            std::cout << "Element Name: " << elementName << std::endl;

            // Iterate through element attributes
            for (const XMLAttribute* attribute = element->FirstAttribute(); 
                 attribute; 
                 attribute = attribute->Next()) {
                const char* attributeName = attribute->Name();
                const char* attributeValue = attribute->Value();
                std::cout << "Attribute: " << attributeName << " = " << attributeValue << std::endl;
            }

            // Get element text content
            const char* text = element->GetText();
            if (text) {
                std::cout << "Text: " << text << std::endl;
            }

            std::cout << std::endl;
        }
    } else {
        std::cout << "Root element not found in the XML document." << std::endl;
    }

    return 0;
}

Key TinyXML2 Methods

  • RootElement(): Gets the root element of the XML document without specifying a name.
  • NextSiblingElement(): Gets the next sibling element at the same level.
  • PreviousSiblingElement(): Gets the previous sibling element at the same level.
  • FirstChildElement(): Gets the first child element of the current element.
  • LastChildElement(): Gets the last child element of the current element.
  • Parent(): Gets the parent element of the current element.
  • DeleteChild(): Removes a child element.
  • GetText(): Retrieves the text content of an element.
  • SetText(): Sets the text content of a element.
  • Name(): Gets the element's name (tag name).
  • Attribute(): Gets an element's attribute value.
  • FirstAttribute(): Gets the first attribute of an element.
  • NextAttribute(): Gets the next attriubte.
  • InsertEndChild(): Inserts a node as the last child of a parent element.
  • InsertFirstChild(): Inserts a node as the first child of a parent element.

For example, in the XML element <property name="ShowQuestClearCount" value="1"/>:

  • Name() returns "property"
  • Attribute("name") returns "ShowQuestClearCount"
  • Attribute("value") returns "1"

Tags: TinyXML2 XML Parsing C++ XML manipulation file processing

Posted on Tue, 08 Sep 2026 16:41:17 +0000 by Akenatehm