C++ 增删改查xml
之前需要下载别人开发好的资源:TinyXML download | SourceForge.net
然后在你的工程中引入以下6个文件,并且在使用的时候包含两个头文件:
下面就是在按钮响应函数中运用了。
创建xml
void BuilderXml() { TiXmlDocument xmlDocument; xmlDocument.LinkEndChild(new TiXmlDeclaration("1.0", "UTF-8", "")); TiXmlElement *XmlRoot = new TiXmlElement("root"); xmlDocument.LinkEndChild(XmlRoot); TiXmlElement *XmlChild1 = new TiXmlElement("name"); XmlRoot->LinkEndChild(XmlChild1); XmlChild1->SetAttribute("id", "0001"); XmlChild1->LinkEndChild(new TiXmlText("value 1")); TiXmlElement *XmlChild2 = new TiXmlElement("name"); XmlRoot->LinkEndChild(XmlChild2); TiXmlElement *XmlChild2_01 = new TiXmlElement("name2"); XmlChild2->LinkEndChild(XmlChild2_01); XmlChild2_01->LinkEndChild(new TiXmlText("value 2_01")); TiXmlElement *XmlChild2_02 = new TiXmlElement("name2"); XmlChild2->LinkEndChild(XmlChild2_02); XmlChild2_02->LinkEndChild(new TiXmlText("value 2_02")); xmlDocument.SaveFile("new.xml"); }
删除xml
void DelXml() { TiXmlDocument xmlDocument; if(!xmlDocument.LoadFile("D:/MFC/XmlParseAndPrint/XmlParseAndPrint/new.xml")) { return; } TiXmlElement *XmlRoot = xmlDocument.RootElement(); TiXmlElement *element = XmlRoot->FirstChildElement("name"); element->RemoveAttribute("id"); XmlRoot->RemoveChild(element); xmlDocument.SaveFile("new.xml"); }
修改xml
void ModifyXml() { TiXmlDocument xmlDocument; if(!xmlDocument.LoadFile("D:/MFC/XmlParseAndPrint/XmlParseAndPrint/new.xml")) { return; } TiXmlElement *XmlRoot = xmlDocument.RootElement(); TiXmlElement *element = XmlRoot->FirstChildElement("name"); element->SetValue("modify"); element->SetAttribute("id", "modify id"); xmlDocument.SaveFile("new.xml"); }
显示xml
void DisplayXml(const char *dbname) { TiXmlDocument xmlDocument; if(!xmlDocument.LoadFile("D:/MFC/XmlParseAndPrint/XmlParseAndPrint/new.xml")) { return; } TiXmlElement *XmlRoot = xmlDocument.RootElement(); for(TiXmlElement *element = XmlRoot->FirstChildElement(dbname); element != NULL; element = element->NextSiblingElement()) { //const char* arr = element->Attribute("name"); const char* node1Name = element->GetText(); for(TiXmlElement *elementChild = element->FirstChildElement(); elementChild != NULL; elementChild = elementChild->NextSiblingElement()) { //const char* name = elementChild->Attribute("name2"); const char* node2Name = elementChild->GetText(); int k = 0; } int j = 0; } }
最后在需要的地方添加函数使用就好了,实际根据需求再修改xml代码