Parsing XML files with tinyxml in C + +

Time:2020-9-2

Tinyxml introduction

Recently, a small load balancing project needs to parse the XML configuration file. Tinyxml is used, which makes it easy to use. A simple example of using tinyxml for XML parsing is given. Many complex applications can be completed based on this example.

Tinyxml is an open source XML parsing library, which can be used in C + +, and can be compiled in windows or Linux. The model of parsing library parses XML file and generates DOM model in memory, which makes it convenient for us to traverse the XML tree.

DOM model is the document object model, which divides the whole document into multiple elements (such as book, chapter, section, paragraph, etc.), and uses tree structure to represent the order relationship and nested inclusion relationship between these elements.

Tinyxml class description

In tinyxml, some classes are defined according to various elements of XML

Tixmlbase: the base class of the entire tinyxml model.

Tixmlattribute: attribute corresponding to the element in XML.

Tixmlnode: corresponds to the node in the DOM structure.

Tixmlcomment: corresponds to the comment in XML.

Tixmldeclaration: corresponds to the declaration part in XML, i.e. <? versiong=”1.0″ ?>。

Tixmldocument: the entire document corresponding to XML.

Tixmlelement: the element corresponding to XML.

Tixmltext: corresponds to the text part of XML.

Tixmlunknown: corresponds to the unknown part of XML.

Tixmlhandler: defines some operations for XML.

Download and compile

Download address: http://sourceforge.net/projects/tinyxml/

The working directory is:

Tinyxml // / working directory
|--Include // header file root
|| -- tinyxml // tinyxml header file, including tinystr. H tinyxml. H
|--Src // CPP source file root directory
  |--Tinyxml // tinyxml source folder, including tinystr.cpp  tinyxml.cpp  tinyxmlerror.cpp  tinyxmlparser.cpp
  |--  main.cpp   //Our main function, call tinyxml sample code 
|--Conf // the folder where the XML file used in our example is located
|--Makefile // Makefile, we don't need to say more about it. If you don't understand, please read the makefile best practices of my blog

Simple examples

Create in the conf directory student.xml code

< school name = "School of software" >
  
  <Class name = "C++"> 
    
    <Student name="tinyxml" number="123"> 
      <email>[email protected]</email> 
      < address > China      
    </Student> 
    
    <Student name="jsoncpp" number="456"> 
      <email>[email protected]</email> 
      < address > U.S. < / address >      
    </Student> 
    
  </Class> 
  
</School>

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

Read the entire XML file and print the code:


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

Read XML

void readSchoolXml() {
  using namespace std;
  const char * xmlFile = "conf/school.xml";
  TiXmlDocument doc;               
  if (doc.LoadFile(xmlFile)) {
    doc.Print();
  } else {
    cout << "can not parse xml conf/school.xml" << endl;
    return;
  }
  
  TiXmlElement* rootElement =  doc.RootElement (); // school element 
  Tixmlelement * classelement = rootelement > firstchildelement(); // class element
  TiXmlElement* studentElement = classElement->FirstChildElement(); //Students 
  
  for (; studentElement != NULL; studentElement = studentElement->NextSiblingElement() ) {
    Tixmlattribute * attributeofstudent = studentelement > firstattribute(); // get the name attribute of student 
    for (;attributeOfStudent != NULL; attributeOfStudent = attributeOfStudent->Next() ) {
      cout << attributeOfStudent->Name() << " : " << attributeOfStudent->Value() << std::endl;    
    }                 

    Tixmlelement * studentcontactelement = studentelement > firstchildelement(); // get the first contact information of the student 
    
    for (; studentContactElement != NULL; studentContactElement = studentContactElement->NextSiblingElement() ) {
      string contactType = studentContactElement->Value();
      string contactValue = studentContactElement->GetText();
      cout << contactType << " : " << contactValue << std::endl;      
    }  
  } 
}

Write XML

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

  TiXmlElement * stu1Element = new TiXmlElement("Student");
  stu1Element->SetAttribute("name", "tinyxml");
  stu1Element->SetAttribute("number", "123");
  TiXmlElement * stu1EmailElement = new TiXmlElement("email");
  stu1EmailElement->LinkEndChild(new TiXmlText("[email protected]") );
  TiXmlElement * stu1AddressElement = new TiXmlElement("address");
  Stu1addresselement > linkendchild (New tixmltext ("China"));
  stu1Element->LinkEndChild(stu1EmailElement);
  stu1Element->LinkEndChild(stu1AddressElement);

  TiXmlElement * stu2Element = new TiXmlElement("Student");
  stu2Element->SetAttribute("name", "jsoncpp");
  stu2Element->SetAttribute("number", "456");
  TiXmlElement * stu2EmailElement = new TiXmlElement("email");
  stu2EmailElement->LinkEndChild(new TiXmlText("[email protected]"));
  TiXmlElement * stu2AddressElement = new TiXmlElement("address");
  Stu2addresselement > linkendchild (New tixmltext ("us"));
  stu2Element->LinkEndChild(stu2EmailElement);
  stu2Element->LinkEndChild(stu2AddressElement);

  classElement->LinkEndChild(stu1Element); 
  classElement->LinkEndChild(stu2Element); 
  schoolElement->LinkEndChild(classElement); 
  
  doc.LinkEndChild(decl); 
  doc.LinkEndChild(schoolElement); 
  doc.SaveFile(xmlFile); 
}

Delete XML operation

Delete a node,TiXmlNodeIs tixmlelement, tixmlcomment, tixmltext, tixmldeclaration, tixmlunknown

Base class of tixmldocument


TiXmlNode node;
node.Clear();

Remove child node B from node a


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

Remove the attribute named B from element a


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

XML modification operation

Search for<mfid val="1234" />Now you need to change 1234 to something else

TiXmlNode* lpnode = NULL;
lpnode = tixml.RootElement()->IterateChildren("mfid",lpnode);
TiXmlAttribute* tiattr = lpnode->ToElement()->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 needed
tiattr->SetValue(mfid.c_str());

Replace a node


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

The above is the details of using tinyxml to parse XML files in C + +. For more information about parsing XML with C + + tinyxml, please pay attention to other related articles in developeppaer!