SoFunction
Updated on 2025-03-05

Parse XML files using TINYXML in c++

TinyXML Introduction

Recently, I have been working on a small load balancing project that requires parsing the XML configuration file. I used TinyXML, which feels very easy to use. I give a simple example of using TinyXML for XML parsing. Many complex applications can be completed based on the methods of this example.

TinyXML is an open source parsing library for parsing XML, which can be used in C++ and can be compiled in Windows or Linux. This parsing library model allows us to easily traverse this XML tree by parsing the XML file and then generating the DOM model in memory.

The DOM model, namely the document object model, divides the entire document into multiple elements (such as books, chapters, sections, paragraphs, etc.), and uses a tree structure to represent the sequential relationship and nested inclusion relationship between these elements.

TinyXML class description

In TinyXML, some classes are defined based on various elements of XML:

TiXmlBase: The base class of the entire TinyXML model.

TiXmlAttribute: The attribute corresponding to an element in XML.

TiXmlNode: Corresponding to nodes in the DOM structure.

TiXmlComment: Correspond to comments in XML.

TiXmlDeclaration: Corresponding to the declaration part in XML, i.e. <? version="1.0" ?>.

TiXmlDocument: The entire document corresponding to the XML.

TiXmlElement: Element corresponding to XML.

TiXmlText: The text part corresponding to the XML.

TiXmlUnknown: Corresponds to unknown parts of XML.

TiXmlHandler: defines some operations for XML.

Download and compile

Download address:/projects/tinyxml/

The working directory is:

tinyxml/      //Work directory|-- include    //Head file root directory|  |-- tinyxml  //tinyxml header file, including|-- src      //CPP source code file root directory|-- tinyxml    //tinyxml source code folder, including|--   //Our main function, sample code for calling tinyxml|-- conf      //The folder where the xml file used in our example is located|-- makefile    //makefile,No need to say more,If you don't understand, please read my blogmakefileBest Practices

Simple example

Create code in the conf directory

&lt;School name="Software Academy"&gt;
  
  &lt;Class name = "C++"&gt; 
    
    &lt;Student name="tinyxml" number="123"&gt; 
      &lt;email&gt;tinyxml@&lt;/email&gt; 
      &lt;address&gt;China&lt;/address&gt;      
    &lt;/Student&gt; 
    
    &lt;Student name="jsoncpp" number="456"&gt; 
      &lt;email&gt;jsoncpp@&lt;/email&gt; 
      &lt;address&gt;USA&lt;/address&gt;      
    &lt;/Student&gt; 
    
  &lt;/Class&gt; 
  
&lt;/School&gt;

To use tinyxml, just include <> in the header file

Read the entire xml file and print the code:

void printSchoolXml() {
  using namespace std;
  TiXmlDocument doc; 
  const char * xmlFile = "conf/";  
  if ((xmlFile)) {  
    (); 
  } else {
    cout << "can not parse xml conf/" << endl;
  }  
}

Read XML

void readSchoolXml() {
  using namespace std;
  const char * xmlFile = "conf/";
  TiXmlDocument doc;               
  if ((xmlFile)) {
    ();
  } else {
    cout &lt;&lt; "can not parse xml conf/" &lt;&lt; endl;
    return;
  }
  
  TiXmlElement* rootElement = (); //School element  TiXmlElement* classElement = rootElement-&gt;FirstChildElement(); // Class element  TiXmlElement* studentElement = classElement-&gt;FirstChildElement(); //Students 
  
  for (; studentElement != NULL; studentElement = studentElement-&gt;NextSiblingElement() ) {
    TiXmlAttribute* attributeOfStudent = studentElement-&gt;FirstAttribute(); //Get the name attribute of student    for (;attributeOfStudent != NULL; attributeOfStudent = attributeOfStudent-&gt;Next() ) {
      cout &lt;&lt; attributeOfStudent-&gt;Name() &lt;&lt; " : " &lt;&lt; attributeOfStudent-&gt;Value() &lt;&lt; std::endl;    
    }                 

    TiXmlElement* studentContactElement = studentElement-&gt;FirstChildElement();//Get the first contact information of student    
    for (; studentContactElement != NULL; studentContactElement = studentContactElement-&gt;NextSiblingElement() ) {
      string contactType = studentContactElement-&gt;Value();
      string contactValue = studentContactElement-&gt;GetText();
      cout &lt;&lt; contactType &lt;&lt; " : " &lt;&lt; contactValue &lt;&lt; std::endl;      
    }  
  } 
}

Write to xml

void writeSchoolXml() {
  using namespace std;
  const char * xmlFile = "conf/"; 
  
  TiXmlDocument doc; 
  TiXmlDeclaration * decl = new TiXmlDeclaration("1.0", "", ""); 
  TiXmlElement * schoolElement = new TiXmlElement( "School" ); 
  TiXmlElement * classElement = new TiXmlElement( "Class" ); 
  classElement-&gt;SetAttribute("name", "C++");

  TiXmlElement * stu1Element = new TiXmlElement("Student");
  stu1Element-&gt;SetAttribute("name", "tinyxml");
  stu1Element-&gt;SetAttribute("number", "123");
  TiXmlElement * stu1EmailElement = new TiXmlElement("email");
  stu1EmailElement-&gt;LinkEndChild(new TiXmlText("tinyxml@") );
  TiXmlElement * stu1AddressElement = new TiXmlElement("address");
  stu1AddressElement-&gt;LinkEndChild(new TiXmlText("China"));
  stu1Element-&gt;LinkEndChild(stu1EmailElement);
  stu1Element-&gt;LinkEndChild(stu1AddressElement);

  TiXmlElement * stu2Element = new TiXmlElement("Student");
  stu2Element-&gt;SetAttribute("name", "jsoncpp");
  stu2Element-&gt;SetAttribute("number", "456");
  TiXmlElement * stu2EmailElement = new TiXmlElement("email");
  stu2EmailElement-&gt;LinkEndChild(new TiXmlText("jsoncpp@"));
  TiXmlElement * stu2AddressElement = new TiXmlElement("address");
  stu2AddressElement-&gt;LinkEndChild(new TiXmlText("USA"));
  stu2Element-&gt;LinkEndChild(stu2EmailElement);
  stu2Element-&gt;LinkEndChild(stu2AddressElement);

  classElement-&gt;LinkEndChild(stu1Element); 
  classElement-&gt;LinkEndChild(stu2Element); 
  schoolElement-&gt;LinkEndChild(classElement); 
  
  (decl); 
  (schoolElement); 
  (xmlFile); 
}

XML deletion operation

Delete a node,TiXmlNodeIt is TiXmlElement, TiXmlComment, TiXmlText, TiXmlDeclaration, TiXmlUnknown,

The base class of TiXmlDocument

TiXmlNode node;
();

Remove child node B from node A

TiXmlNode nodeA;
nodeA. RemoveChild( TiXmlNode* removeThis );

Remove attributes with name B from element A

TiXmlAttribute attrA;
attrA. RemoveAttribute( const char * name );

XML modification operation

Find content as<mfid val="1234" />Now you need to change 1234 to another value

TiXmlNode* lpnode = NULL;
lpnode = ()-&gt;IterateChildren("mfid",lpnode);
TiXmlAttribute* tiattr = lpnode-&gt;ToElement()-&gt;FirstAttribute();
//Find the mfid node and get the first attribute value.  Note that if there are multiple attribute values, you need to determine which attribute value is required.tiattr-&gt;SetValue(mfid.c_str());

Replace a node

TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis );

The above is the detailed content of using TINYXML to parse XML files in c++. For more information about c++ tinyxml parsing XML, please pay attention to my other related articles!