### Install Configuration Files Source: https://github.com/leethomason/tinyxml2/blob/master/CMakeLists.txt Installs the main TinyXML2 CMake configuration files. ```cmake install( FILES "${CMAKE_CURRENT_SOURCE_DIR}/cmake/tinyxml2-config.cmake" "${CMAKE_CURRENT_BINARY_DIR}/tinyxml2-config-version.cmake" DESTINATION "${tinyxml2_INSTALL_CMAKEDIR}" COMPONENT tinyxml2_development ) ``` -------------------------------- ### Installation Directories Source: https://github.com/leethomason/tinyxml2/blob/master/CMakeLists.txt Includes standard CMake modules for installation and defines custom installation directory variables. ```cmake ## Standard modules include(GNUInstallDirs) include(CMakePackageConfigHelpers) ## Custom settings option(tinyxml2_INSTALL_PKGCONFIG "Create and install pkgconfig files" ON) set(tinyxml2_INSTALL_PKGCONFIGDIR "${CMAKE_INSTALL_LIBDIR}/pkgconfig" CACHE PATH "Directory for pkgconfig files") set(tinyxml2_INSTALL_CMAKEDIR "${CMAKE_INSTALL_LIBDIR}/cmake/tinyxml2" CACHE STRING "Path to tinyxml2 CMake files") ``` -------------------------------- ### Install Header File Source: https://github.com/leethomason/tinyxml2/blob/master/CMakeLists.txt Installs the main TinyXML2 header file. ```cmake install( FILES tinyxml2.h TYPE INCLUDE COMPONENT tinyxml2_development ) ``` -------------------------------- ### Install and Compile TinyXML2 Manually Source: https://context7.com/leethomason/tinyxml2/llms.txt Instructions for installing TinyXML2 using vcpkg and a basic command for manual compilation using g++. ```bash # vcpkg installation git clone https://github.com/Microsoft/vcpkg.git cd vcpkg && ./bootstrap-vcpkg.sh ./vcpkg install tinyxml2 # Manual compilation (g++) g++ -Wall main.cpp tinyxml2.cpp -o myapp ``` -------------------------------- ### Configure and Install Pkg-config File Source: https://github.com/leethomason/tinyxml2/blob/master/CMakeLists.txt Configures and installs the pkg-config file for TinyXML2 if enabled. ```cmake if (tinyxml2_INSTALL_PKGCONFIG) configure_file(cmake/tinyxml2.pc.in tinyxml2.pc.gen @ONLY) file(GENERATE OUTPUT tinyxml2.pc INPUT "${CMAKE_CURRENT_BINARY_DIR}/tinyxml2.pc.gen") install( FILES "${CMAKE_CURRENT_BINARY_DIR}/tinyxml2.pc" DESTINATION "${tinyxml2_INSTALL_PKGCONFIGDIR}" COMPONENT tinyxml2_development ) endif () ``` -------------------------------- ### Install Library Target Source: https://github.com/leethomason/tinyxml2/blob/master/CMakeLists.txt Installs the tinyxml2 library target, specifying components for runtime and development. ```cmake install( TARGETS tinyxml2 EXPORT tinyxml2-targets RUNTIME COMPONENT tinyxml2_runtime LIBRARY COMPONENT tinyxml2_runtime NAMELINK_COMPONENT tinyxml2_development ARCHIVE COMPONENT tinyxml2_development INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" ) ``` -------------------------------- ### XML Declaration Example Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_declaration.html An example of an XML declaration. TinyXML-2 reads and writes this as a string. ```xml ``` -------------------------------- ### Project and Version Setup Source: https://github.com/leethomason/tinyxml2/blob/master/CMakeLists.txt Sets the minimum CMake version and defines the project name and version. ```cmake cmake_minimum_required(VERSION 3.15) project(tinyxml2 VERSION 11.0.0) ``` -------------------------------- ### OpenElement() Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_printer.html Starts writing an XML element when streaming. ```APIDOC ## OpenElement() ### Description If streaming, start writing an element. The element must be closed with CloseElement(). ### Parameters * **_name_** (const char*) - The name of the element to open. * **_compactMode_** (bool) - Optional - If true, this specific element will be opened in compact mode. ``` -------------------------------- ### XMLHandle Copy Example Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_handle.html Illustrates that XMLHandles can be safely copied, as they are essentially lightweight wrappers around node pointers. ```cpp XMLHandle handleCopy = handle; ``` -------------------------------- ### Concise XML Traversal Example Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_handle.html Demonstrates the conciseness of XMLHandle for navigating the XML tree, avoiding verbose null checks. ```cpp XMLHandle docHandle( &document ); XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement(); if ( child2 ) { // do something useful } ``` -------------------------------- ### Install Export Scripts Source: https://github.com/leethomason/tinyxml2/blob/master/CMakeLists.txt Installs CMake export scripts for the tinyxml2 targets, with a namespace and type-specific filename. ```cmake if (BUILD_SHARED_LIBS) set(type shared) else () set(type static) endif () install( EXPORT tinyxml2-targets DESTINATION "${tinyxml2_INSTALL_CMAKEDIR}" NAMESPACE tinyxml2:: FILE tinyxml2-${type}-targets.cmake COMPONENT tinyxml2_development ) ``` -------------------------------- ### Accept Visitor Pattern Example Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_declaration.html Demonstrates using the Accept() method to apply the visitor pattern to the XML tree. This allows for hierarchical traversal and callback via the XMLVisitor interface. ```cpp XMLPrinter printer; tinyxmlDoc.Accept( &printer ); const char* xmlcstr = printer.CStr(); ``` -------------------------------- ### Opening an XML Element Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_printer.html OpenElement starts a new XML element with the given name. It can optionally be used in compact mode. ```cpp void OpenElement( const char* name, bool compactMode = false ); ``` -------------------------------- ### XMLNode Deep Clone Example Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_node.html Illustrates creating a deep copy of an XMLNode and its children. The cloned nodes can be allocated in the current document or a specified target document. ```cpp XMLNode* clone = node->DeepClone(targetDocument); ``` -------------------------------- ### Find and Link TinyXML2 Library Source: https://github.com/leethomason/tinyxml2/blob/master/test/CMakeLists.txt This snippet shows how to find the TinyXML2 package and link it to an executable. Ensure TinyXML2 is installed or available in the CMake search path. ```cmake cmake_minimum_required(VERSION 3.15) project(tinyxml2-test) enable_testing() find_package(tinyxml2 REQUIRED) add_executable(xmltest ../xmltest.cpp) target_link_libraries(xmltest PRIVATE tinyxml2::tinyxml2) ``` -------------------------------- ### Compile TinyXML-2 with Debug Assertions Source: https://context7.com/leethomason/tinyxml2/llms.txt This command compiles TinyXML-2 and a test application with debug assertions enabled. Ensure you have g++ installed and the TinyXML-2 source files. ```bash g++ -Wall -DTINYXML2_DEBUG tinyxml2.cpp xmltest.cpp -o xmltest ``` -------------------------------- ### XMLNode Get User Data Example Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_node.html An inline function to retrieve the user-defined data pointer associated with an XMLNode. This allows attaching custom data to nodes. ```cpp void* userData = node->GetUserData(); ``` -------------------------------- ### XMLNode Set User Data Example Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_node.html Sets a user-defined data pointer for an XMLNode. This is useful for associating external data with specific nodes in the XML tree. ```cpp node->SetUserData( myData ); ``` -------------------------------- ### Parse XML and Get Text Source: https://github.com/leethomason/tinyxml2/blob/master/docs/_example_3.html Parses an XML string and retrieves text content from a specific element. Always check for null pointers in production code. ```cpp int example_3() { static const char* xml = "" "" "" "A Midsummer Night's Dream" ""; XMLDocument doc; doc.Parse( xml ); XMLElement* titleElement = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" ); const char* title = titleElement->GetText(); printf( "Name of play (1): %s\n", title ); return 0; } ``` -------------------------------- ### Building and Integration with CMake and vcpkg Source: https://context7.com/leethomason/tinyxml2/llms.txt Provides instructions on how to integrate the TinyXML2 library into a C++ project using CMake, either by directly adding source files or using vcpkg for package management. Manual compilation with g++ is also shown. ```APIDOC ## Building and Integration TinyXML-2 integrates into any C++ project by adding two files, with optional CMake or vcpkg support. ```cmake # CMakeLists.txt — embed directly into your project cmake_minimum_required(VERSION 3.10) project(MyApp) # Option 1: Add source files directly add_executable(MyApp main.cpp tinyxml2.cpp tinyxml2.h ) # Option 2: Use as a subdirectory (if tinyxml2 CMakeLists.txt is present) add_subdirectory(tinyxml2) target_link_libraries(MyApp PRIVATE tinyxml2) # Option 3: Install via vcpkg, then find_package find_package(tinyxml2 CONFIG REQUIRED) target_link_libraries(MyApp PRIVATE tinyxml2::tinyxml2) ``` ```bash # vcpkg installation git clone https://github.com/Microsoft/vcpkg.git cd vcpkg && ./bootstrap-vcpkg.sh ./vcpkg install tinyxml2 # Manual compilation (g++) g++ -Wall main.cpp tinyxml2.cpp -o myapp ``` ``` -------------------------------- ### Parent Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_document.html Get the parent of this node on the DOM. ```APIDOC ## Parent ### Description Get the parent of this node on the DOM. ### Method const [XMLNode](classtinyxml2_1_1_x_m_l_node.html) * Parent () const ### Return Value Returns a pointer to the parent node, or null if this node has no parent. ``` -------------------------------- ### Load and Parse XML File Source: https://github.com/leethomason/tinyxml2/blob/master/docs/index.html Demonstrates the basic usage of loading and parsing an XML file using XMLDocument.LoadFile(). ```cpp { XMLDocument doc; doc.LoadFile( "dream.xml" ); } ``` -------------------------------- ### XMLNode::Parent Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Gets the parent of this node in the DOM. ```APIDOC ## XMLNode::Parent ### Description Get the parent of this node on the DOM. ### Signature ```cpp const XMLNode * Parent() const ``` ### Definition tinyxml2.h:758 ``` -------------------------------- ### GetUserData Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_document.html Get user data pointer for this node. ```APIDOC ## GetUserData ### Description Get user data pointer for this node. ### Method void * GetUserData () const ### Return Value Returns the pointer to user-defined data. ``` -------------------------------- ### XMLDocument Load, Parse, and Save Source: https://context7.com/leethomason/tinyxml2/llms.txt Demonstrates parsing XML from a string, loading from a file, saving to a file (pretty-printed and compact), printing to stdout, serializing to a memory string, handling whitespace modes, deep copying, and error inspection. ```cpp #include "tinyxml2.h" using namespace tinyxml2; // --- Parse from string --- const char* xmlStr = "" "" " " " " ""; XMLDocument doc; XMLError result = doc.Parse(xmlStr); if (result != XML_SUCCESS) { printf("Parse error: %s\n", doc.ErrorStr()); return; } // --- Load from file --- XMLDocument doc2; if (doc2.LoadFile("config.xml") != XML_SUCCESS) { doc2.PrintError(); // prints to stdout return; } // --- Save to file --- doc2.SaveFile("config_out.xml"); // pretty-printed doc2.SaveFile("config_compact.xml", true); // compact (no extra whitespace) // --- Print to stdout --- doc2.Print(); // uses default XMLPrinter // --- Serialize to memory string --- XMLPrinter printer; doc2.Print(&printer); const char* xmlOutput = printer.CStr(); // null-terminated XML string printf("%s\n", xmlOutput); // --- Whitespace modes --- // PRESERVE_WHITESPACE (default), COLLAPSE_WHITESPACE, PEDANTIC_WHITESPACE XMLDocument docCollapsed(true, COLLAPSE_WHITESPACE); docCollapsed.Parse(" hello world "); // Text node value will be "hello world" (collapsed) // --- Deep copy a document --- XMLDocument copy; doc.DeepCopy(©); // --- Error inspection --- if (doc.Error()) { printf("Error ID : %d\n", doc.ErrorID()); printf("Error Name: %s\n", doc.ErrorName()); printf("Error Str : %s\n", doc.ErrorStr()); printf("Error Line: %d\n", doc.ErrorLineNum()); } doc.ClearError(); ``` -------------------------------- ### XMLNode::PreviousSibling Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Gets the previous sibling node of this node. ```APIDOC ## XMLNode::PreviousSibling ### Description Get the previous (left) sibling node of this node. ### Signature ```cpp const XMLNode * PreviousSibling() const ``` ### Definition tinyxml2.h:808 ``` -------------------------------- ### Accept() Method Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_unknown.html Accepts a hierarchical visit of the nodes in the TinyXML-2 DOM using the XMLVisitor interface. This provides a SAX-like interface for traversing the XML tree. ```cpp virtual bool tinyxml2::XMLUnknown::Accept( XMLVisitor* _visitor ) const ``` -------------------------------- ### NextSibling Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_document.html Get the next (right) sibling node of this node. ```APIDOC ## NextSibling ### Description Get the next (right) sibling node of this node. ### Method const [XMLNode](classtinyxml2_1_1_x_m_l_node.html) * NextSibling () const ### Return Value Returns a pointer to the next sibling node, or null if this node has no next sibling. ``` -------------------------------- ### Lookup XML Information with TinyXML-2 Source: https://github.com/leethomason/tinyxml2/blob/master/docs/index.html Demonstrates how to load an XML file and retrieve text content from elements using two different methods: a convenience function and a more general approach involving XMLText nodes. Error checking is omitted for brevity. ```cpp { XMLDocument doc; doc.LoadFile( "dream.xml" ); // Structure of the XML file: // - Element "PLAY" the root Element, which is the // FirstChildElement of the Document // - - Element "TITLE" child of the root PLAY Element // - - - Text child of the TITLE Element // Navigate to the title, using the convenience function, // with a dangerous lack of error checking. const char* title = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" )->GetText(); printf( "Name of play (1): %s\n", title ); // Text is just another Node to TinyXML-2. The more // general way to get to the XMLText: XMLText* textNode = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" )->FirstChild()->ToText(); title = textNode->Value(); printf( "Name of play (2): %s\n", title ); } ``` -------------------------------- ### PreviousSibling Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_document.html Get the previous (left) sibling node of this node. ```APIDOC ## PreviousSibling ### Description Get the previous (left) sibling node of this node. ### Method const [XMLNode](classtinyxml2_1_1_x_m_l_node.html) * PreviousSibling () const ### Return Value Returns a pointer to the previous sibling node, or null if this node has no previous sibling. ``` -------------------------------- ### Accept Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_declaration.html Accepts a visitor and dispatches the visit to the correct visitor method. This is part of the Visitor pattern. ```APIDOC virtual bool Accept(tinyxml2::XMLVisitor* visitor) const override ``` -------------------------------- ### XMLNode::LastChild Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Gets the last child node, or null if none exists. ```APIDOC ## XMLNode::LastChild ### Description Get the last child node, or null if none exists. ### Signature ```cpp const XMLNode * LastChild() const ``` ### Definition tinyxml2.h:790 ``` -------------------------------- ### Main Library Build Settings Source: https://github.com/leethomason/tinyxml2/blob/master/CMakeLists.txt Configures C++ visibility for the library. Use this to control symbol visibility. ```cmake set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN YES) ``` -------------------------------- ### tinyxml2::XMLHandle::NextSibling Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Gets a handle to the next sibling of the current node. ```APIDOC ## NextSibling ### Description Gets a handle to the next sibling of this handle. ### Signature `XMLHandle NextSibling()` ### Returns * `XMLHandle` - A handle to the next sibling node. ``` -------------------------------- ### tinyxml2::XMLHandle::LastChild Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Gets a handle to the last child of the current node. ```APIDOC ## LastChild ### Description Gets a handle to the last child of this handle. ### Signature `XMLHandle LastChild()` ### Returns * `XMLHandle` - A handle to the last child node. ``` -------------------------------- ### LoadFile (FILE*) Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_document.html Loads an XML file from a FILE pointer. The caller is responsible for providing and closing the FILE. The file should be opened in binary mode ('rb'). Returns XML_SUCCESS on success or an error ID. ```APIDOC ## LoadFile (FILE*) ### Description Load an XML file from disk. You are responsible for providing and closing the FILE*. NOTE: The file should be opened as binary ("rb") not text in order for TinyXML-2 to correctly do newline normalization. Returns XML_SUCCESS (0) on success, or an errorID. ### Method Signature `XMLError tinyxml2::XMLDocument::LoadFile(FILE *)` ``` -------------------------------- ### Accept Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_document.html Accepts an XMLVisitor to traverse the XML document structure. ```APIDOC ## Accept ### Description Accepts an XMLVisitor to traverse the XML document structure. This is part of the Visitor design pattern. ### Method virtual bool Accept(XMLVisitor *visitor) const override ### Parameters - **visitor** (XMLVisitor *) - A pointer to the XMLVisitor object. ### Returns bool - True if the visitor accepted the node, false otherwise. ``` -------------------------------- ### tinyxml2::XMLHandle::FirstChild Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Gets a handle to the first child of the current node. ```APIDOC ## FirstChild ### Description Gets a handle to the first child of this handle. ### Signature `XMLHandle FirstChild()` ### Returns * `XMLHandle` - A handle to the first child node. ``` -------------------------------- ### Minimal XML Document Loading and Parsing Source: https://context7.com/leethomason/tinyxml2/llms.txt This C++ snippet demonstrates the minimal code required to load an XML file, check for errors, and access the root element. It also shows how to access TinyXML-2 version constants. ```cpp // Minimal integration — main.cpp #include "tinyxml2.h" using namespace tinyxml2; int main() { XMLDocument doc; if (doc.LoadFile("config.xml") != XML_SUCCESS) { doc.PrintError(); return 1; } XMLElement* root = doc.RootElement(); printf("Root element: %s\n", root->Name()); // Version constants available at compile time printf("TinyXML-2 version: %d.%d.%d\n", TINYXML2_MAJOR_VERSION, // 11 TINYXML2_MINOR_VERSION, // 0 TINYXML2_PATCH_VERSION); // 0 return 0; } ``` -------------------------------- ### tinyxml2::XMLHandle::PreviousSibling Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Gets a handle to the previous sibling of the current node. ```APIDOC ## PreviousSibling ### Description Gets a handle to the previous sibling of this handle. ### Signature `XMLHandle PreviousSibling()` ### Returns * `XMLHandle` - A handle to the previous sibling node. ``` -------------------------------- ### XMLDocument Create New Nodes Source: https://context7.com/leethomason/tinyxml2/llms.txt Shows how to create new XML nodes (declaration, elements, attributes, text, comments) using factory methods on XMLDocument and insert them into the document tree. Demonstrates convenience methods like InsertNewChildElement and inserting before/after existing siblings. ```cpp #include "tinyxml2.h" using namespace tinyxml2; XMLDocument doc; // Create the XML declaration XMLDeclaration* decl = doc.NewDeclaration(); // doc.InsertFirstChild(decl); // Create root element XMLElement* root = doc.NewElement("library"); doc.InsertEndChild(root); // Create child element with attributes XMLElement* book = doc.NewElement("book"); book->SetAttribute("id", 42); book->SetAttribute("available", true); book->SetAttribute("price", 9.99); root->InsertEndChild(book); // Create text content XMLElement* title = doc.NewElement("title"); title->SetText("The C++ Programming Language"); book->InsertEndChild(title); // Create comment XMLComment* comment = doc.NewComment("Added in 2024"); book->InsertEndChild(comment); // Convenience: InsertNewChildElement (creates + appends in one call) XMLElement* author = book->InsertNewChildElement("author"); author->SetText("Bjarne Stroustrup"); // Insert before an existing sibling XMLElement* isbn = doc.NewElement("isbn"); isbn->SetText("978-0321563842"); book->InsertAfterChild(title, isbn); // order: title, isbn, comment, author doc.SaveFile("library.xml"); // Output: // // // // The C++ Programming Language // 978-0321563842 // // Bjarne Stroustrup // // ``` -------------------------------- ### Attribute and QueryAttribute Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Methods for getting and querying attribute values of an XML element. ```APIDOC ## Attribute and QueryAttribute ### Description Provides methods to retrieve attribute values by name, with options for default values and error checking. ### Methods - **const char* Attribute(const char *name, const char *value = 0) const**: Returns the value of the named attribute. - **bool BoolAttribute(const char *name, bool defaultValue = false) const**: Retrieves a boolean attribute. - **uint64_t Unsigned64Attribute(const char *name, uint64_t defaultValue = 0) const**: Retrieves an unsigned 64-bit integer attribute. - **int64_t Int64Attribute(const char *name, int64_t defaultValue = 0) const**: Retrieves a signed 64-bit integer attribute. - **XMLError QueryAttribute(const char *name, int *value) const**: Queries for an integer attribute and returns an error code. - **XMLError QueryUnsignedAttribute(const char *name, unsigned int *value) const**: Queries for an unsigned integer attribute and returns an error code. - **XMLError QueryDoubleAttribute(const char *name, double *value) const**: Queries for a double-precision floating-point attribute and returns an error code. - **XMLError QueryInt64Attribute(const char *name, int64_t *value) const**: Queries for a signed 64-bit integer attribute and returns an error code. ### Parameters - **name** (const char *) - The name of the attribute to retrieve. - **value** (int *, unsigned int *, double *, int64_t *) - Pointer to store the retrieved attribute value. - **defaultValue** (bool | uint64_t | int64_t) - The default value to return if the attribute is not found. ### See Also - IntAttribute() - QueryIntAttribute() - QueryDoubleAttribute() - QueryInt64Attribute() - QueryUnsignedAttribute() ``` -------------------------------- ### Print XML to a File using XMLPrinter Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_printer.html Provide a file pointer to the XMLPrinter constructor to direct XML output to a specific file. The document is then printed using the provided printer. ```cpp XMLPrinter printer( fp ); doc.Print( &printer ); ``` -------------------------------- ### XMLUtil::IsPrefixHex Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Checks if a string starts with a hexadecimal prefix (e.g., '0x'). ```APIDOC ## IsPrefixHex ### Description Checks if a C-string, after skipping leading whitespace, begins with a hexadecimal prefix ('0x' or '0X'). ### Method `inline static bool IsPrefixHex( const char* p);` ### Parameters - `p` (const char*) - The C-string to check. ### Returns `true` if the string has a hexadecimal prefix, `false` otherwise. ``` -------------------------------- ### Accept Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_comment.html Accepts a visitor and dispatches the visit to the appropriate XMLComment-specific visitor function. This is part of the Visitor design pattern. ```APIDOC virtual bool Accept(tinyxml2::XMLVisitor* visitor) const override Accepts a visitor. ``` -------------------------------- ### XMLUtil::IsNameStartChar Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Checks if a character is a valid starting character for an XML name. ```APIDOC ## IsNameStartChar ### Description Checks if a character is a valid starting character for an XML name according to XML naming rules. This includes alphabetic characters, underscore, and colon. ### Method `inline static bool IsNameStartChar( unsigned char ch );` ### Parameters - `ch` (unsigned char) - The character to check. ### Returns `true` if the character is a valid name start character, `false` otherwise. ``` -------------------------------- ### XMLElement::Name Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Gets the name of the element. The name is equivalent to the node's Value(). ```APIDOC ## XMLElement::Name ### Description Gets the name of the element. The name is equivalent to the node's Value(). ### Signature const char * Name() const ### Returns (const char*) - The name of the element. ``` -------------------------------- ### Clone XML Nodes and Documents Source: https://context7.com/leethomason/tinyxml2/llms.txt Demonstrates deep copying an entire XML document and deep cloning a single XML node into another document. Also shows shallow cloning and shallow equality checks. ```cpp #include "tinyxml2.h" using namespace tinyxml2; const char* xml = "" " Widget" " Gadget" ""; XMLDocument src; src.Parse(xml); // --- Deep copy entire document --- XMLDocument dest; src.DeepCopy(&dest); // dest is now a fully independent copy of src // --- Deep clone a single subtree into another document --- XMLDocument dest2; XMLElement* srcRoot = src.RootElement(); XMLElement* firstProduct = srcRoot->FirstChildElement("product"); // Clone into dest2 (allocates in dest2's memory pool) XMLNode* clonedNode = firstProduct->DeepClone(&dest2); XMLElement* clonedProduct = clonedNode->ToElement(); dest2.InsertEndChild(clonedProduct); // Modify clone without affecting source clonedProduct->SetAttribute("id", 99); clonedProduct->FirstChildElement("name")->SetText("Clone Widget"); // --- Shallow clone (node only, no children) --- XMLDocument dest3; XMLNode* shallowCopy = firstProduct->ShallowClone(&dest3); // shallowCopy has no children // --- Equality check (shallow, no children compared) --- bool equal = firstProduct->ShallowEqual(shallowCopy); // true XMLPrinter p; dest.Print(&p); printf("%s\n", p.CStr()); ``` -------------------------------- ### PreviousSiblingElement Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_document.html Get the previous (left) sibling element of this node, with an optionally supplied name. ```APIDOC ## PreviousSiblingElement ### Description Get the previous (left) sibling element of this node, with an optionally supplied name. ### Method const [XMLElement](classtinyxml2_1_1_x_m_l_element.html) * PreviousSiblingElement (const char * name=0) const ### Parameters * **name** (const char *) - Optional name of the element to find. ### Return Value Returns a pointer to the previous sibling element with the specified name, or null if none is found. ``` -------------------------------- ### Load XML File with TinyXML-2 Source: https://github.com/leethomason/tinyxml2/blob/master/docs/_example_1.html Use this snippet to load an XML file from disk. Check the return value of ErrorID() for success (0 indicates no error). ```c++ int example_1() { XMLDocument doc; doc.LoadFile( "resources/dream.xml" ); return doc.ErrorID(); } ``` -------------------------------- ### Text Manipulation and Querying Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Functions for getting, setting, and querying the text content of an XML element. ```APIDOC ## GetText ### Description Retrieves the text content of the XML element. ### Method const char* ### Return Value A C-style string representing the text content, or nullptr if no text is present. ### Method Signature const char* GetText() const; ``` ```APIDOC ## SetText (various overloads) ### Description Sets the text content of the XML element. Overloaded to accept different data types. ### Method void ### Parameters - **inText** (const char*) - The text content as a C-style string. - **value** (int) - The integer value to set as text. - **value** (unsigned) - The unsigned integer value to set as text. - **value** (int64_t) - The 64-bit integer value to set as text. - **value** (uint64_t) - The 64-bit unsigned integer value to set as text. - **value** (bool) - The boolean value to set as text. - **value** (double) - The double-precision floating-point value to set as text. - **value** (float) - The single-precision floating-point value to set as text. ### Method Signatures void SetText( const char* inText ); void SetText( int value ); void SetText( unsigned value ); void SetText( int64_t value ); void SetText( uint64_t value ); void SetText( bool value ); void SetText( double value ); void SetText( float value ); ``` ```APIDOC ## QueryIntText ### Description Attempts to query the text content as an integer. ### Method XMLError ### Parameters - **ival** (int*) - A pointer to an integer where the result will be stored. ### Return Value XMLError indicating success or failure. ### Method Signature XMLError QueryIntText( int* ival ) const; ``` ```APIDOC ## QueryUnsignedText ### Description Attempts to query the text content as an unsigned integer. ### Method XMLError ### Parameters - **uval** (unsigned*) - A pointer to an unsigned integer where the result will be stored. ### Return Value XMLError indicating success or failure. ### Method Signature XMLError QueryUnsignedText( unsigned* uval ) const; ``` ```APIDOC ## QueryInt64Text ### Description Attempts to query the text content as a 64-bit integer. ### Method XMLError ### Parameters - **uval** (int64_t*) - A pointer to a 64-bit integer where the result will be stored. ### Return Value XMLError indicating success or failure. ### Method Signature XMLError QueryInt64Text( int64_t* uval ) const; ``` ```APIDOC ## QueryUnsigned64Text ### Description Attempts to query the text content as a 64-bit unsigned integer. ### Method XMLError ### Parameters - **uval** (uint64_t*) - A pointer to a 64-bit unsigned integer where the result will be stored. ### Return Value XMLError indicating success or failure. ### Method Signature XMLError QueryUnsigned64Text( uint64_t* uval ) const; ``` ```APIDOC ## QueryBoolText ### Description Attempts to query the text content as a boolean. ### Method XMLError ### Parameters - **bval** (bool*) - A pointer to a boolean where the result will be stored. ### Return Value XMLError indicating success or failure. ### Method Signature XMLError QueryBoolText( bool* bval ) const; ``` ```APIDOC ## QueryDoubleText ### Description Attempts to query the text content as a double-precision floating-point number. ### Method XMLError ### Parameters - **dval** (double*) - A pointer to a double where the result will be stored. ### Return Value XMLError indicating success or failure. ### Method Signature XMLError QueryDoubleText( double* dval ) const; ``` ```APIDOC ## QueryFloatText ### Description Attempts to query the text content as a single-precision floating-point number. ### Method XMLError ### Parameters - **fval** (float*) - A pointer to a float where the result will be stored. ### Return Value XMLError indicating success or failure. ### Method Signature XMLError QueryFloatText( float* fval ) const; ``` ```APIDOC ## IntText ### Description Retrieves the text content as an integer, returning a default value if parsing fails or no text exists. ### Method int ### Parameters - **defaultValue** (int) - The value to return if the text cannot be parsed as an integer (defaults to 0). ### Return Value The integer representation of the text content or the default value. ### Method Signature int IntText(int defaultValue = 0) const; ``` ```APIDOC ## UnsignedText ### Description Retrieves the text content as an unsigned integer, returning a default value if parsing fails or no text exists. ### Method unsigned ### Parameters - **defaultValue** (unsigned) - The value to return if the text cannot be parsed as an unsigned integer (defaults to 0). ### Return Value The unsigned integer representation of the text content or the default value. ### Method Signature unsigned UnsignedText(unsigned defaultValue = 0) const; ``` ```APIDOC ## Int64Text ### Description Retrieves the text content as a 64-bit integer, returning a default value if parsing fails or no text exists. ### Method int64_t ### Parameters - **defaultValue** (int64_t) - The value to return if the text cannot be parsed as a 64-bit integer (defaults to 0). ### Return Value The 64-bit integer representation of the text content or the default value. ### Method Signature int64_t Int64Text(int64_t defaultValue = 0) const; ``` ```APIDOC ## Unsigned64Text ### Description Retrieves the text content as a 64-bit unsigned integer, returning a default value if parsing fails or no text exists. ### Method uint64_t ### Parameters - **defaultValue** (uint64_t) - The value to return if the text cannot be parsed as a 64-bit unsigned integer (defaults to 0). ### Return Value The 64-bit unsigned integer representation of the text content or the default value. ### Method Signature uint64_t Unsigned64Text(uint64_t defaultValue = 0) const; ``` ```APIDOC ## BoolText ### Description Retrieves the text content as a boolean, returning a default value if parsing fails or no text exists. ### Method bool ### Parameters - **defaultValue** (bool) - The value to return if the text cannot be parsed as a boolean (defaults to false). ### Return Value The boolean representation of the text content or the default value. ### Method Signature bool BoolText(bool defaultValue = false) const; ``` ```APIDOC ## DoubleText ### Description Retrieves the text content as a double-precision floating-point number, returning a default value if parsing fails or no text exists. ### Method double ### Parameters - **defaultValue** (double) - The value to return if the text cannot be parsed as a double (defaults to 0). ### Return Value The double-precision floating-point representation of the text content or the default value. ### Method Signature double DoubleText(double defaultValue = 0) const; ``` ```APIDOC ## FloatText ### Description Retrieves the text content as a single-precision floating-point number, returning a default value if parsing fails or no text exists. ### Method float ### Parameters - **defaultValue** (float) - The value to return if the text cannot be parsed as a float (defaults to 0). ### Return Value The single-precision floating-point representation of the text content or the default value. ### Method Signature float FloatText(float defaultValue = 0) const; ``` -------------------------------- ### XMLDocument - Load, Parse, and Save Source: https://context7.com/leethomason/tinyxml2/llms.txt Demonstrates how to load XML from a string or file, parse it into an `XMLDocument` object, and then save the document back to a file or serialize it to a string. It also covers error inspection and whitespace handling. ```APIDOC ## XMLDocument - Load, Parse, and Save `XMLDocument` is the top-level object that owns all nodes. It can load XML from a file path, a `FILE*`, or a char buffer, and save back to disk or to memory via `XMLPrinter`. ```cpp #include "tinyxml2.h" using namespace tinyxml2; // --- Parse from string --- const char* xmlStr = "" "" " " " " ""; XMLDocument doc; XMLError result = doc.Parse(xmlStr); if (result != XML_SUCCESS) { printf("Parse error: %s\n", doc.ErrorStr()); return; } // --- Load from file --- XMLDocument doc2; if (doc2.LoadFile("config.xml") != XML_SUCCESS) { doc2.PrintError(); // prints to stdout return; } // --- Save to file --- doc2.SaveFile("config_out.xml"); // pretty-printed doc2.SaveFile("config_compact.xml", true); // compact (no extra whitespace) // --- Print to stdout --- doc2.Print(); // uses default XMLPrinter // --- Serialize to memory string --- XMLPrinter printer; doc2.Print(&printer); const char* xmlOutput = printer.CStr(); // null-terminated XML string printf("%s\n", xmlOutput); // --- Whitespace modes --- // PRESERVE_WHITESPACE (default), COLLAPSE_WHITESPACE, PEDANTIC_WHITESPACE XMLDocument docCollapsed(true, COLLAPSE_WHITESPACE); docCollapsed.Parse(" hello world "); // Text node value will be "hello world" (collapsed) // --- Deep copy a document --- XMLDocument copy; doc.DeepCopy(©); // --- Error inspection --- if (doc.Error()) { printf("Error ID : %d\n", doc.ErrorID()); printf("Error Name: %s\n", doc.ErrorName()); printf("Error Str : %s\n", doc.ErrorStr()); printf("Error Line: %d\n", doc.ErrorLineNum()); } doc.ClearError(); ``` ``` -------------------------------- ### XMLPrinter Constructor Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_printer.html The XMLPrinter constructor initializes the printer. It can optionally take a file pointer for direct file output and a boolean to enable compact mode. ```cpp XMLPrinter( FILE* file = 0, bool compact = false, int depth = 0 ); ``` -------------------------------- ### tinyxml2::XMLHandle::NextSiblingElement Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Gets a handle to the next sibling element of the current node, optionally filtered by name. ```APIDOC ## NextSiblingElement ### Description Gets a handle to the next sibling element of this handle. If a name is provided, it returns the next sibling element with that specific name. ### Signature `XMLHandle NextSiblingElement(const char *name = 0)` ### Parameters * **name** (const char*) - Optional name of the sibling element to find. ### Returns * `XMLHandle` - A handle to the next sibling element. ``` -------------------------------- ### Accept Visitor Pattern Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_element.html Implements the Accept method for the Visitor pattern, allowing hierarchical traversal of the XML DOM via an XMLVisitor interface. This provides a SAX-like interface without re-parsing. ```cpp virtual bool tinyxml2::XMLElement::Accept ( [XMLVisitor](classtinyxml2_1_1_x_m_l_visitor.html) * _visitor_ ) const overridevirtual Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the XML tree will be conditionally visited and the host will be called back via the [XMLVisitor](classtinyxml2_1_1_x_m_l_visitor.html) interface. This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this interface versus any other.) The interface has been based on ideas from: * [http://www.saxproject.org/](http://www.saxproject.org/) * [http://c2.com/cgi/wiki?HierarchicalVisitorPattern](http://c2.com/cgi/wiki?HierarchicalVisitorPattern) Which are both good references for "visiting". An example of using [Accept()](#acae4a763d74c13ce4a31eb70b4db9f82): XMLPrinter printer; ``` -------------------------------- ### tinyxml2::XMLComment::Accept Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_comment-members.html Accepts a visitor and calls the appropriate visitor method. ```APIDOC ## tinyxml2::XMLComment::Accept ### Description Accepts a visitor and calls the appropriate visitor method. ### Method virtual ### Parameters * **visitor** (*XMLVisitor* *) - The visitor object. ### Returns void ``` -------------------------------- ### tinyxml2::XMLHandle::PreviousSiblingElement Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Gets a handle to the previous sibling element of the current node, optionally filtered by name. ```APIDOC ## PreviousSiblingElement ### Description Gets a handle to the previous sibling element of this handle. If a name is provided, it returns the previous sibling element with that specific name. ### Signature `XMLHandle PreviousSiblingElement(const char *name = 0)` ### Parameters * **name** (const char*) - Optional name of the sibling element to find. ### Returns * `XMLHandle` - A handle to the previous sibling element. ``` -------------------------------- ### tinyxml2::XMLHandle::FirstChildElement Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Gets a handle to the first child element of the current node, optionally filtered by name. ```APIDOC ## FirstChildElement ### Description Gets a handle to the first child element of this handle. If a name is provided, it returns the first child element with that specific name. ### Signature `XMLHandle FirstChildElement(const char *name = 0)` ### Parameters * **name** (const char*) - Optional name of the child element to find. ### Returns * `XMLHandle` - A handle to the first child element. ``` -------------------------------- ### tinyxml2::XMLHandle::LastChildElement Source: https://github.com/leethomason/tinyxml2/blob/master/docs/tinyxml2_8h_source.html Gets a handle to the last child element of the current node, optionally filtered by name. ```APIDOC ## LastChildElement ### Description Gets a handle to the last child element of this handle. If a name is provided, it returns the last child element with that specific name. ### Signature `XMLHandle LastChildElement(const char *name = 0)` ### Parameters * **name** (const char*) - Optional name of the child element to find. ### Returns * `XMLHandle` - A handle to the last child element. ``` -------------------------------- ### Get Next Sibling Handle Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_handle.html Retrieves a handle to the next sibling node of the current handle's node. ```cpp XMLHandle NextSibling() ``` -------------------------------- ### Integrate TinyXML2 with CMake Source: https://context7.com/leethomason/tinyxml2/llms.txt Provides CMake configurations for embedding TinyXML2 directly into a project, using it as a subdirectory, or linking against a vcpkg-installed version. ```cmake # CMakeLists.txt — embed directly into your project cmake_minimum_required(VERSION 3.10) project(MyApp) # Option 1: Add source files directly add_executable(MyApp main.cpp tinyxml2.cpp tinyxml2.h ) # Option 2: Use as a subdirectory (if tinyxml2 CMakeLists.txt is present) add_subdirectory(tinyxml2) target_link_libraries(MyApp PRIVATE tinyxml2) # Option 3: Install via vcpkg, then find_package find_package(tinyxml2 CONFIG REQUIRED) target_link_libraries(MyApp PRIVATE tinyxml2::tinyxml2) ``` -------------------------------- ### Get Previous Sibling Handle Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_handle.html Retrieves a handle to the previous sibling node of the current handle's node. ```cpp XMLHandle PreviousSibling() ``` -------------------------------- ### XMLElement::Accept Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_element-members.html Accepts a visitor and calls the appropriate visitor method. ```APIDOC ## XMLElement::Accept ### Description Accepts a visitor and calls the appropriate visitor method. ### Method `virtual bool Accept(XMLVisitor *visitor) const override` ### Parameters * **visitor** (*XMLVisitor* *) - A pointer to the XMLVisitor object. ``` -------------------------------- ### Get Last Child Handle Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_handle.html Retrieves a handle to the last child node of the current handle's node. ```cpp XMLHandle LastChild() ``` -------------------------------- ### Get First Child Handle Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_handle.html Retrieves a handle to the first child node of the current handle's node. ```cpp XMLHandle FirstChild() ``` -------------------------------- ### Build Test Executable Source: https://github.com/leethomason/tinyxml2/blob/master/CMakeLists.txt Builds the 'xmltest' executable if testing is enabled. Links it against the tinyxml2 library. ```cmake if (tinyxml2_BUILD_TESTING) add_executable(xmltest xmltest.cpp) target_link_libraries(xmltest PRIVATE tinyxml2::tinyxml2) add_test( NAME xmltest COMMAND xmltest WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" ) set_tests_properties(xmltest PROPERTIES PASS_REGULAR_EXPRESSION ", Fail 0") endif () ``` -------------------------------- ### Copy Constructor for XMLHandle Source: https://github.com/leethomason/tinyxml2/blob/master/docs/classtinyxml2_1_1_x_m_l_handle.html Creates a new XMLHandle by copying an existing one. Handles are lightweight and can be safely copied. ```cpp XMLHandle( const XMLHandle& ref ) ```