#include "tinyxml2.h" //创建一个XML void CreateXml() { //添加根元素root tinyxml2::XMLDocument* doc = new tinyxml2::XMLDocument(); tinyxml2::XMLElement* root = doc->NewElement( "root" ); doc->InsertFirstChild(root); //添加child元素element并设置属性 tinyxml2::XMLElement* element = doc->NewElement( "element" ); element->SetAttribute("key1", "abc"); element->SetAttribute("key2", "123"); element->SetAttribute("key3", "abc"); root->InsertFirstChild(element); element = doc->NewElement( "element" ); element->SetAttribute("key1", "efg"); element->SetAttribute("key2", "456"); element->SetAttribute("key3", "efg"); root->LinkEndChild(element); element = doc->NewElement( "element" ); element->SetAttribute("key1", "efg1"); element->SetAttribute("key2", "4567"); element->SetAttribute("key3", "efg1"); root->LinkEndChild(element); //添加child元素text并设置text element = doc->NewElement( "text" ); element->SetText("hello world"); root->LinkEndChild(element); doc->Print(); doc->SaveFile("test.xml"); delete doc; } void ReadXml() { tinyxml2::XMLDocument doc; doc.LoadFile("test.xml"); if (0 != doc.ErrorID()) { printf("[errorId=%d, file=%s]load xml file fail\n", doc.ErrorID(), "example.xml"); return; } tinyxml2::XMLElement* elementRoot = doc.FirstChildElement("root"); if (NULL == elementRoot) { printf("xml element elementRoot not exist\n"); return; } tinyxml2::XMLElement* element = elementRoot->FirstChildElement("element"); while( element != NULL) { const char* key1 = NULL; element->QueryStringAttribute("key1", &key1); printf("key1:%s ", key1); int key2 = 0; element->QueryIntAttribute("key2", &key2); printf("key2:%d ", key2); const char* key3 = 0; element->QueryStringAttribute("key3", &key3); printf("key3:%s\n", key3); element = element->NextSiblingElement(); } element = elementRoot->FirstChildElement("text"); const char* str = element->GetText(); printf("<text>%s</text>\n", str); } int main() { CreateXml(); ReadXml(); return 0; }
标签:tinyxml2,key3,doc,SetAttribute,element,tinyxml,使用,样板,root From: https://www.cnblogs.com/ho966/p/17975501