C++使用TinyXML2实现解析和生成XML数据

  #include

  #include

  #include

  int main(){

  tinyxml2::XMLDocument xmlObj;

  // 解析数据

  //const char* xmlData = "";

  //tinyxml2::XMLError errCode = xmlObj.Parse(xmlData);

  // 解析文件

  tinyxml2::XMLError errCode = xmlObj.LoadFile("xmldata.txt");

  if(errCode != tinyxml2::XML_SUCCESS){

  printf("LoadFile xml failed, errCode = %d

  ", errCode);

  return -1;

  }

  // 获取根节点

  tinyxml2::XMLElement* root = xmlObj.RootElement();

  if (!root) {

  std::cout << "Invalid document structure." << std::endl;

  return -1;

  }

  // msg_id

  tinyxml2::XMLElement* msgidElem = root->FirstChildElement("msg_id");

  if(msgidElem != NULL){

  const char* cMsgid = msgidElem->GetText();

  printf("cMsgid: %s

  ", cMsgid);

  }

  // 遍历header元素

  for (tinyxml2::XMLElement* headerElem = root->FirstChildElement("header"); headerElem != nullptr; headerElem = headerElem->NextSiblingElement("header")) {

  // 获取属性

  const char* cHattr = headerElem->Attribute("hattr");

  printf("cHattr: %s

  ", cHattr);

  // 获取字段值

  tinyxml2::XMLElement* typeElem = headerElem->FirstChildElement("type");

  if(typeElem != NULL){

  const char* cType = typeElem->GetText();

  printf("cType: %s

  ", cType);

  }

  tinyxml2::XMLElement* hostElem = headerElem->FirstChildElement("host");

  if(hostElem != NULL){

  const char* cHost = hostElem->GetText();

  printf("cHost: %s

  ", cHost);

  }

  }

  // 遍历body元素

  for (tinyxml2::XMLElement* bodyElem = root->FirstChildElement("body"); bodyElem != nullptr; bodyElem = bodyElem->NextSiblingElement("body")) {

  // 获取属性

  const char* cBattr = bodyElem->Attribute("battr");

  printf("cBattr: %s

  ", cBattr);

  // 获取字段值

  tinyxml2::XMLElement* dataElem = bodyElem->FirstChildElement("data");

  if(dataElem != NULL){

  const char* cData = dataElem->GetText();

  printf("cData: %s

  ", cData);

  }

  }

  return 0;

  }