TinyXml创建XMl的两种方法,以及属性添加

【转载】TinyXml创建XMl的两种方法,以及属性添加
文章转自:http://blog.sina.com.cn/s/blog_69e905cd0100ks5v.html

第一种方法:

 TiXmlDocument *pDoc= new TiXmlDocument;  // 定义一个文档的指针
 
// 添加一个xml头。
 TiXmlDeclaration *pDeclaration= new TiXmlDeclaration("1.0","UTF-8","");
 pDoc->LinkEndChild(pDeclaration);
  // 添加XMl的根节点
 TiXmlElement *lengquan=  new TiXmlElement("lengquan");
 pDoc->LinkEndChild(lengquan);
  // 添加一个父节点
 TiXmlNode *parent=  new TiXmlElement("qiu");
 TiXmlNode* name4NewNode =  new TiXmlElement("name");
 parent->InsertEndChild(*name4NewNode)->InsertEndChild(TiXmlText("pipi")); 
 TiXmlNode* addr4NewNode =  new TiXmlElement("addr");
 parent->InsertEndChild(*addr4NewNode)->InsertEndChild(TiXmlText("Shaanxi Xianyang"));
 TiXmlNode* tel4NewNode =  new TiXmlElement("tel");
 parent->InsertEndChild(*tel4NewNode)->InsertEndChild(TiXmlText("02937310627"));
 TiXmlNode* email4NewNode =  new TiXmlElement("email");
 parent->InsertEndChild(*email4NewNode)->InsertEndChild(TiXmlText([email protected]));
 lengquan->InsertEndChild(*parent);   


 pDoc->SaveFile("lengquan.xml");

第二种方法:

//  TODO: Add your control notification handler code here
 TiXmlDocument *pDoc= new TiXmlDocument;  // 定义一个文档的指针
 
// 添加一个xml头。
 TiXmlDeclaration *pDeclaration= new TiXmlDeclaration("1.0","UTF-8","");
 pDoc->LinkEndChild(pDeclaration);
  // 添加XMl的根节点
 TiXmlElement *lengquan=  new TiXmlElement("lengquan");
 pDoc->LinkEndChild(lengquan);
  // 添加xml父节点,其实父节点跟子节点一样,这里为了我自己明白的更清楚一点,所以我自己称根节点的下一结点为父节点。
 TiXmlElement *parent= new TiXmlElement("qiu");
 lengquan->LinkEndChild(parent);
  // 添加属性
 parent->SetAttribute("time","12:10");

  // 添加子节点。
 TiXmlElement *name4NewNode= new TiXmlElement("name");
 parent->LinkEndChild(name4NewNode);
  // 添加节点下文本
 CString strName="pipi";
 TiXmlText *pNameValue= new TiXmlText(strName);
 name4NewNode->LinkEndChild(pNameValue);
 
  //
 TiXmlElement* addr4NewNode= new TiXmlElement("addr");
 parent->LinkEndChild(addr4NewNode);

 CString strAddr="Shaanxi Xianyang";
 TiXmlText *pAddrValue= new TiXmlText(strAddr);
 parent->LinkEndChild(pAddrValue);
  //
 TiXmlElement* tel4NewNode= new TiXmlElement("tel");
 parent->LinkEndChild(tel4NewNode);

 CString strTel="02937310627";
 TiXmlText *pTelValue= new TiXmlText(strTel);
 parent->LinkEndChild(pTelValue);

  // 保存
 pDoc->SaveFile("lengquan1.xml");

 

相对而言我更趋向于第二种写法。

你可能感兴趣的:(TinyXml创建XMl的两种方法,以及属性添加)