TinyXml库 使用方法

xiaoxiao2021-02-28  44

TinyXml下载链接:https://pan.baidu.com/s/1kXiTFSF

使用TinyXML只需要将其中的6个文件拷贝到项目中就可以直接使用了,这六个文件是:tinyxml.h、tinystr.h、tinystr.cpp、tinyxml.cpp、tinyxmlerror.cpp、tinyxmlparser.cpp;

TinyXml类介绍:

    XmlBase:整个TinyXML模型的基类;

     XmlAttribute:对应于XML中的元素的属性;

    XmlComment:对应于XML中的注释;

    XmlDeclaration:对应于XML中的申明部分,即<?versiong="1.0" ?>;

    XmlDocument:对应于XML的整个文档;

    XmlDocument:对应于XML的整个文档;

    XmlText:对应于XML的文字部分;

    XmlUnknown:对应于XML的未知部分;

    XmlHandler:定义了针对XML的一些操作;

备注:元素一定是节点,节点不一定是元素;

一:加载XML文件

//加载XML文件 TiXmlDocument doc; if(!doc.LoadFile("test.xml")) { qDebug()<<"加载XML文件失败"; const char *errorStr = doc.ErrorDesc(); qDebug()<<errorStr; //打印失败原因; }

二:获取XML的根节点

//加载XML文件 TiXmlDocument doc; if(!doc.LoadFile("test.xml")) { qDebug()<<"加载XML文件失败"; const char *errorStr = doc.ErrorDesc(); qDebug()<<errorStr; //打印失败原因; } else { //获取根节点元素 TiXmlElement *root = doc.FirstChildElement(); }

三:常用方法

        TiXmlDocument doc; doc.LoadFile("test.xml"); TiXmlElement *root = doc.FirstChildElement(); //获取根节点元素 QString ElementName = root->Value(); //获取元素名 bool Children = root->NoChildren(); //判断该元素是否有子元素 返回true 有,false 没有 TiXmlElement *child = root->FirstChildElement(); //获取root元素下的第一个子元素 child = root->FirstChildElement("major"); //获取root元素的子元素指定元素名字(major) TiXmlElement *brother = child->NextSiblingElement(); //获取child元素的下一个兄弟元素 brother = child->NextSiblingElement("specVersion"); //获取child元素的兄弟元素指定元素名字(specVersion) QString text = brother->GetText(); //获取brother元素的值 TiXmlAttribute *Attribute = brother->FirstAttribute(); //获取brother元素的第一个属性 QString AttributeName = Attribute->Name(); //获取Attribute属性的名字 QString AttributeValue = Attribute->Value(); //获取Attribute属性的值 AttributeValue = brother->Attribute("AttributeName"); //获取brother的属性名为(AttributeName)的值     TiXmlDocument *myDocument = new TiXmlDocument(); //创建一个XML文件 TiXmlDeclaration *pDeclaration=new TiXmlDeclaration("1.0","UTF-8",""); //创建xml文件头(<?xml version="1.0" encoding="UTF-8" ?>) myDocument->LinkEndChild(pDeclaration); //加入将xml文件头加入文档中 TiXmlElement *BUSINESS=new TiXmlElement("BUSINESS"); //创建一个元素节点 myDocument->LinkEndChild(BUSINESS); //加入BUSINESS元素节点到文档中 TiXmlElement *COUNTRY = new TiXmlElement("COUNTRY"); //创建两个节点 TiXmlElement *PLANET = new TiXmlElement("PLANET"); BUSINESS->LinkEndChild(PLANET); //将新建的节点加到BUSINESS下一级 BUSINESS->LinkEndChild(COUNTRY); TiXmlText *PLANETtxt = new TiXmlText("one"); //添加节点内的文本 TiXmlText *COUNTRYtxt = new TiXmlText("china"); COUNTRY->LinkEndChild(COUNTRYtxt); PLANET->LinkEndChild(PLANETtxt); myDocument->SaveFile("test.xml"); //保存xml

    

    

转载请注明原文地址: https://www.6miu.com/read-2619556.html

最新回复(0)