c++中用TINYXML解析XML文件

2020-06-05 15:00:13王冬梅

写入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("tinyxml@163.com") );
  TiXmlElement * stu1AddressElement = new TiXmlElement("address");
  stu1AddressElement->LinkEndChild(new TiXmlText("中国"));
  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("jsoncpp@163.com"));
  TiXmlElement * stu2AddressElement = new TiXmlElement("address");
  stu2AddressElement->LinkEndChild(new TiXmlText("美国"));
  stu2Element->LinkEndChild(stu2EmailElement);
  stu2Element->LinkEndChild(stu2AddressElement);

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

XML删除操作

删除某个节点, TiXmlNode是TiXmlElement、TiXmlComment、TiXmlText、TiXmlDeclaration、TiXmlUnknown、

TiXmlDocument的基类

TiXmlNode node;
node.Clear();

从A节点上移除子节点B

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

从元素A上移除名字为B的属性

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

XML修改操作

查找内容为<mfid val="1234" />现需要将1234改成其他值

TiXmlNode* lpnode = NULL;
lpnode = tixml.RootElement()->IterateChildren("mfid",lpnode);
TiXmlAttribute* tiattr = lpnode->ToElement()->FirstAttribute();
//找到mfid节点,获取第一个属性值。注意,如果有多个属性值,需要判断哪个属性值是需要的
tiattr->SetValue(mfid.c_str());

替换一个节点

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

以上就是c++中用TINYXML解析XML文件的详细内容,更多关于c++ tinyxml解析XML的资料请关注易采站长站其它相关文章!