cmeel-tinyxml2: Python Bindings for TinyXML-2

10.0.0 · active · verified Thu Apr 16

cmeel-tinyxml2 provides efficient Python bindings for TinyXML-2, a small, fast, and simple C++ XML parser. It allows Python developers to leverage the underlying C++ library's performance for parsing, creating, and manipulating XML documents directly from Python. The current version is 10.0.0, with releases typically aligning with upstream TinyXML-2 updates and the `cmeel` packaging cycle.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a new XML document, add elements, attributes, and text, and then print its content. It also shows how to parse an existing XML string and navigate its elements, including checking for parsing errors using TinyXML-2's error handling API.

import tinyxml2
import os

# Create a new document
doc = tinyxml2.XMLDocument()

# Add a declaration (optional but good practice)
doc.InsertEndChild(doc.NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\""))

# Create a root element
root = doc.NewElement("Root")
doc.InsertEndChild(root)

# Add a child element with an attribute and text
child = doc.NewElement("Item")
child.SetAttribute("id", 123)
child.SetText("Example Text")
root.InsertEndChild(child)

# Add another child
another_child = doc.NewElement("SubItem")
another_child.SetText("More data")
child.InsertEndChild(another_child)

# Print the document to stdout
printer = tinyxml2.XMLPrinter()
doc.Print(printer)
print("\n--- Generated XML ---")
print(printer.CStr())

# Example of parsing an XML string
xml_string = "<data><item value='parsed_value'/></data>"
parsed_doc = tinyxml2.XMLDocument()
parsed_doc.Parse(xml_string)

print("\n--- Parsed XML Content ---")
if not parsed_doc.Error():
    root_element = parsed_doc.FirstChildElement("data")
    if root_element:
        item_element = root_element.FirstChildElement("item")
        if item_element:
            print(f"Parsed item value: {item_element.Attribute('value')}")
        else:
            print("Item element not found.")
    else:
        print("Data root element not found.")
elif parsed_doc.ErrorID() == tinyxml2.XML_NO_ERROR:
    print("Parsing completed with no document errors, but might be empty.")
else:
    print(f"Parsing error: {parsed_doc.ErrorStr()} (ID: {parsed_doc.ErrorID()})")

# Example of saving to a file (optional, requires write access)
# output_filename = "output.xml"
# if os.environ.get('ENABLE_FILE_WRITE', '0') == '1': # Use env var for safety
#     if doc.SaveFile(output_filename):
#         print(f"XML successfully saved to {output_filename}")
#     else:
#         print(f"Error saving XML to {output_filename}: {doc.ErrorStr()}")

view raw JSON →