TinyXML中部分函數的使用

void AddNewTest()
{
 //添加一個完整結點
 TiXmlElement *pEle = NULL;
 TiXmlNode *pNode = NULL;


 TiXmlDocument XMLDoc("AddInfo.xml");

 /*
  首先添加一個頭部申明
 */
 TiXmlDeclaration *pDeclearation = new TiXmlDeclaration( "1.0","utf-8", "yes" ); //這部分內存不需要外部刪除
 XMLDoc.LinkEndChild(pDeclearation); //將內存交給TinyXML釋放

 /*
  添加根節點,使用InsertEndChild
 */
 TiXmlElement *pRootEle = new TiXmlElement("ROOT");
 TiXmlText *pText = new TiXmlText("");

 pNode = XMLDoc.LinkEndChild(pRootEle);
 pEle = pNode->ToElement();
 pNode = pEle->InsertEndChild(*pText); //該部分內存需要自己釋放

 /*
  使用 InsertAfterChild 方法添加結點
 */
 TiXmlElement *pChildEle = new TiXmlElement("first child");
 pChildEle->SetAttribute("attr1",123);
 pChildEle->SetAttribute("attr2", "first");
 pNode = pRootEle->InsertAfterChild(pNode, *pChildEle);
 pEle = pNode->ToElement();
 pEle->InsertEndChild(*pText);

 /*
  使用 InsertEndChild 添加結點
 */
 DeleteSpecAttr(pChildEle, "attr2");
 pChildEle->SetAttribute("attr2", "second-add"); //添加需要修改的值
 pNode = pRootEle->InsertBeforeChild(pNode, *pChildEle);
 pEle = pNode->ToElement();
 pEle->InsertEndChild(*pText);

 /*
      設置結點的值 SetValue
 */
 DeleteSpecAttr(pChildEle, "attr2");
 pNode = pRootEle->InsertAfterChild(pNode, *pChildEle);
 pEle = pNode->ToElement();
 pText->SetValue("setvalue");  //設置結點的值
 pEle->InsertEndChild(*pText);


 if (pChildEle)
 {
  delete pChildEle;
  pChildEle = NULL;
 }

 if (pText)
 {
  delete pText;
  pText = NULL;
 }


 XMLDoc.Print();

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章