TinyXML入门教程
tinyxml用法

tinyxml用法TinyXML是一个用于解析和生成XML文件的C++库。
它提供了一组简单且易于使用的API,可将XML文档解析为树状结构,让用户可以通过遍历这棵树来获取和修改XML文件中的内容。
本文将详细介绍TinyXML的使用方法,包括如何解析XML文件、访问节点、修改节点内容以及生成XML 文件等。
一、解析XML文件1.引入头文件和命名空间要使用TinyXML,首先需要引入头文件tinyxml.h:#include <tinyxml.h>然后在代码中使用命名空间:using namespace std;using namespace tinyxml2;2.打开并解析XML文件创建一个XML文档对象以及一个错误代码对象,然后调用LoadFile(方法打开并解析XML文件:XMLDocument doc;doc.LoadFile("example.xml");3.获取根节点使用RootElement(方法获取根节点:XMLElement* root = doc.RootElement(;4.遍历子节点可以使用FirstChildElement(方法获取第一个子节点,然后使用NextSiblingElement(方法依次获取下一个兄弟节点,直到遍历完所有子节点:for (XMLElement* child = root->FirstChildElement(; child != NULL; child = child->NextSiblingElement()//对子节点进行操作5.获取节点属性和内容使用Attribute(方法获取节点的属性值,使用GetText(方法获取节点的文本内容:const char* attributeValue = node->Attribute("属性名");const char* textContent = node->GetText(;二、访问和修改节点1.创建新节点可以使用NewElement(方法创建一个新节点,然后将其添加到指定节点的子节点列表中:XMLElement* newNode = doc.NewElement("节点名称");parentNode->InsertEndChild(newNode);2.修改节点属性和内容使用SetAttribute(方法设置节点的属性值,使用SetText(方法设置节点的文本内容:node->SetAttribute("属性名", "属性值");node->SetText("文本内容");3.删除节点使用DeleteChildren(方法删除节点的所有子节点:node->DeleteChildren(;4.复制节点可以使用CloneNode(方法复制一个节点:XMLElement* newNode = node->CloneNode(true);三、生成XML文件1.创建一个XML文档对象XMLDocument doc;2.创建根节点使用NewElement(方法创建一个根节点并将其添加到文档中:XMLElement* root = doc.NewElement("根节点名称");doc.InsertEndChild(root);3.创建子节点使用NewElement(方法创建一个子节点并将其添加到根节点的子节点列表中:XMLElement* child = doc.NewElement("子节点名称");root->InsertEndChild(child);4.创建属性使用SetAttribute(方法设置节点的属性值:child->SetAttribute("属性名", "属性值");5.创建文本内容使用SetText(方法设置节点的文本内容:child->SetText("文本内容");6.保存XML文件使用SaveFile(方法将XML文档保存为文件:doc.SaveFile("example.xml");以上就是TinyXML库的基本用法。
TinyXml查找唯一节点及修改节点操作

TinyXml查找唯一节点及修改节点操作TinyXml查找唯一节点及修改节点操作分类: C++ 算法 2012-10-17 23:22 238人阅读评论(0) 收藏举报[cpp]view plaincopy?1.// 读者对象:对TinyXml有一定了解的人。
本文是对TinyXml 工具的一些知识点的理解。
2.// 1 TinyXml中对TiXmlNode进行了分类,是用一个枚举进行描述的。
3.// enum NodeType4.// {5.// DOCUMENT, 文档节点6.// ELEMENT, 元素节点7.// COMMENT, 还没弄清楚8.// UNKNOWN, 未知节点9.// TEXT, 文本节点10.// DECLARATION, 声明节点11.// TYPECOUNT 还没弄清楚12.// };13.// TiXmlNode * pNode->Type() 函数可以返回节点的类型。
14.// 枚举的比较方法:TiXmlText::TEXT == pNode->Type();15.//16.// 这几个类型非常重要,尤其是在遍历xml时或者查找一个节点时17.// 我对节点和元素的理解如下:为了说明问题,我使用下面的xml文档来举例说明18.// <?xml version="1.0" encoding="gb2312"?>19.// <Persons>20.// <person Id="200" Shengao=34 ClassName="计本0508">21.// <name>vertor</name>22.// <age>20</age>23.// <address encode="utf-8">24.// <country>中国</country>25.// <province>山西</province>26.// <village>王大庄</village>27.// </address>28.// </person>29.// </Persons>30.//31.// 2.1 节点:一种对文档结构的描述对象32.// 2.2 元素:对文档某一个数据块的描述33.// 2.3 文本是指没有孩子的节点34.// 例如<village>大王庄</village> 文本节点是:"大王庄"35.// 然而判断一个节点是否是文本节点时并不是根据pNode->NoChildren()来判断,而是根据节点的类型来判断36.// 因为如果一个节点形如:<village></village>它也是没有孩子节点的。
TIXML使用详解

TiXmlNode* pChild;
TiXmlText* pText; int t = pParent->Type(); printf( "type %d/n", t); int num;
switch ( t ) { case TiXmlNode::DOCUMENT:
<name>TinyXml How To</name> <price unit=”RMB”>20</price> <description>Some words…</description> </ book > 整个文档,对应 TiXmlDocument book,name,price, description,都对应 TiXmlElement 第一行对应一个 TiXmlDeclaration 第二行对应一个 TiXmlComment “TinyXml How To”对应一个 TiXmlText unit 则是 price 的一个 TiXmlAttribute 这些类与 XML 文件中的相应元素都有很好的对应关系,因此相信参照 TinyXml 的文档,可以 很容易的掌握各个方法的使用。 2. 需要注意的问题 各类之间的转换 由于各个节点类都从 TiXmlNode 继承,在使用时常常需要将 TiXmlNode*类型的指针转换为 其派生类的指针,在进行这种转换时,应该首先使用由 TiXmlNode 类提供的一系列转换函数, 如 ToElement(void),而不是 c++的 dynamic_cast。 检查返回值 由于 TinyXml 是一个非校验的解析器,因此当解析一个文件时,很可能文件并不包含我们预 期的某个节点,在这种情况下,TinyXml 将返回空指针。因此,必须要对返回值进行检查, 否则将很容易出现内存访问的错误。 如何重头建立一个 XML 文件 先建立一个 TiXmlDocument 对象,然后,载入某个模板,或者直接插入一个节点作为根节点, 接着就可以像打开一个已有的 XML 文件那样对它进行操作了。
XML基础教程(Tutorials Point)说明书

About the T utorialXML stands for Ex tensible M arkup L anguage and is a text-based markup language derived from Standard Generalized Markup Language (SGML).This tutorial will teach you the basics of XML. The tutorial is divided into sections such as XML Basics, Advanced XML, and XML tools. Each of these sections contain related topics with simple and useful examples.AudienceThis reference has been prepared for beginners to help them understand the basic to advanced concepts related to XML. This tutorial will give you enough understanding on XML from where you can take yourself to a higher level of expertise. PrerequisitesBefore proceeding with this tutorial, you should have basic knowledge of HTML and JavaScript.Copyright & DisclaimerCopyright 2018 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher.We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or inthistutorial,******************************************T able of ContentsAbout the Tutorial (i)Audience (i)Prerequisites (i)Copyright & Disclaimer (i)Table of Contents (ii)XML BASICS (1)1.XML – Overview (2)XML Usage (2)What is Markup? (3)Is XML a Programming Language? (3)2.XML – Syntax (4)3.XML – Documents (9)Document Prolog Section (9)Document Elements Section (10)4.XML – Declaration (11)5.XML – Tags (14)Start Tag (14)End Tag (14)Empty Tag (14)XML Tags Rules (15)6.XML – Elements (16)Empty Element (16)XML Elements Rules (17)7.XML – Attributes (18)Attribute Types (19)Element Attribute Rules (20)8.XML – Comments (21)XML Comments Rules (21)9.XML – Character Entities (22)Types of Character Entities (22)10.XML – CDATA Sections (24)CDATA Rules (25)11.XML – Whitespaces (26)Significant Whitespace (26)Insignificant Whitespace (26)12.XML – Processing (27)Processing Instructions Rules (28)13.XML – Encoding (29)Encoding Types (29)14.XML – Validation (31)Well-formed XML Document (31)Valid XML Document (32)ADVANCE XML (33)15.XML – DTDs (34)Internal DTD (34)External DTD (36)Types (37)16.XML – Schemas (39)Definition Types (40)17.XML – Tree Structure (42)18.XML – DOM (45)19.XML – Namespaces (47)Namespace Declaration (47)20.XML – Databases (48)XML Database Types (48)XML- Enabled Database (48)XML TOOLS (50)21.XML – Viewers (51)Text Editors (51)Firefox Browser (52)Chrome Browser (52)Errors in XML Document (52)22.XML – Editors (54)Open Source XML Editors (54)23.XML – Parsers (55)24.XML – Processors (56)Types (56)XML Basics11.XML stands for E xtensible M arkup L anguage. It is a text-based markup language derived from Standard Generalized Markup Language (SGML).XML tags identify the data and are used to store and organize the data, rather than specifying how to display it like HTML tags, which are used to display the data. XML is not going to replace HTML in the near future, but it introduces new possibilities by adopting many successful features of HTML.There are three important characteristics of XML that make it useful in a variety of systems and solutions:∙XML is extensible: XML allows you to create your own self-descriptive tags or language, that suits your application.∙XML carries the data, does not present it: XML allows you to store the data irrespective of how it will be presented.∙XML is a public standard: XML was developed by an organization called the World Wide Web Consortium (W3C) and is available as an open standard.XML UsageA short list of XML usage says it all:∙XML can work behind the scene to simplify the creation of HTML documents for large web sites.∙XML can be used to exchange the information between organizations and systems.∙XML can be used for offloading and reloading of databases.∙XML can be used to store and arrange the data, which can customize your data handling needs.∙XML can easily be merged with style sheets to create almost any desired output.∙Virtually, any type of data can be expressed as an XML document.2What is Markup?XML is a markup language that defines set of rules for encoding documents in a format that is both human-readable and machine-readable. So, what exactly is a markup language? Markup is information added to a document that enhances its meaning in certain ways, in that it identifies the parts and how they relate to each other. More specifically, a markup language is a set of symbols that can be placed in the text of a document to demarcate and label the parts of that document.Following example shows how XML markup looks, when embedded in a piece of text:This snippet includes the markup symbols, or the tags such as <message>...</message> and <text>... </text>. The tags <message> and </message> mark the start and the end of the XML code fragment. The tags <text> and </text> surround the text Hello, world!. Is XML a Programming Language?A programming language consists of grammar rules and its own vocabulary which is used to create computer programs. These programs instruct the computer to perform specific tasks. XML does not qualify to be a programming language as it does not perform any computation or algorithms. It is usually stored in a simple text file and is processed by special software that is capable of interpreting XML.32.In this chapter, we will discuss the simple syntax rules to write an XML document. Following is a complete XML document:You can notice, there are two kinds of information in the above example: ∙Markup, like <contact-info>∙The text, or the character data, Tutorials Point and (040) 123-4567The following diagram depicts the syntax rules to write different types of markup and text in an XML document.Let us see each component of the above diagram in detail.4XML DeclarationThe XML document can optionally have an XML declaration. It is written as follows:Where version is the XML version and encoding specifies the character encoding used in the document.Syntax Rules for XML Declaration∙The XML declaration is case sensitive and must begin with "<?xml>" where "xml"is written in lower-case.∙If the document contains XML declaration, then it strictly needs to be the first statement of the XML document.∙The XML declaration strictly needs be the first statement in the XML document.∙An HTTP protocol can override the value of encoding that you put in the XML declaration.T ags and ElementsAn XML file is structured by several XML-elements, also called XML-nodes or XML-tags. The names of XML-elements are enclosed in triangular brackets < > as shown below:Syntax Rules for Tags and ElementsElement Syntax: Each XML-element needs to be closed either with start or with end elements as shown below:or in simple-cases, just this way:Nesting of Elements: An XML-element can contain multiple XML-elements as its children, but the children elements must not overlap. i.e., an end tag of an element must have the same name as that of the most recent unmatched start tag.56The following example shows incorrect nested tags:The following example shows correct nested tags:Root Element: An XML document can have only one root element. For example, following is not a correct XML document, because both the x andy elements occur at the top level without a root element:The following example shows a correctly formed XML document:Case Sensitivity: The names of XML-elements are case-sensitive. That means the name of the start and the end elements need to be exactly in the same case.For example, <contact-info> is different from <Contact-Info>.XML AttributesAn attribute specifies a single property for the element, using a name/value pair. An XML-element can have one or more attributes. For example:Here href is the attribute name and / is attribute value.Syntax Rules for XML Attributes∙Attribute names in XML (unlike HTML) are case sensitive. That is,HREF and href are considered two different XML attributes.∙Same attribute cannot have two values in a syntax. The following example shows incorrect syntax because the attribute b is specified twice:∙Attribute names are defined without quotation marks, whereas attribute values must always appear in quotation marks. Following example demonstrates incorrect xml syntax:In the above syntax, the attribute value is not defined in quotation marks.XML ReferencesReferences usually allow you to add or include additional text or markup in an XML document. References always begin with the symbol "&" which is a reserved character and end with the symbol ";". XML has two types of references:∙Entity References: An entity reference contains a name between the start and the end delimiters. For example, & where amp is name. The name refers toa predefined string of text and/or markup.∙Character References: These contain references, such as A, contains a hash mark (“#”) followed by a number. The number always refers to the Unicode code of a character. In this case, 65 refers to alphabet "A".XML T extThe names of XML-elements and XML-attributes are case-sensitive, which means the name of start and end elements need to be written in the same case. To avoid character encoding problems, all XML files should be saved as Unicode UTF-8 or UTF-16 files.Whitespace characters like blanks, tabs and line-breaks between XML-elements and between the XML-attributes will be ignored.Some characters are reserved by the XML syntax itself. Hence, they cannot be used directly. To use them, some replacement-entities are used, which are listed below:783.An XML document is a basic unit of XML information composed of elements and other markup in an orderly package. An XML document can contain a wide variety of data. For example, database of numbers, numbers representing molecular structure or a mathematical equation.XML Document ExampleA simple document is shown in the following example:The following image depicts the parts of XML document.Document Prolog SectionDocument Prolog comes at the top of the document, before the root element. This section contains:∙XML declaration∙Document type declarationYou can learn more about XML declaration in this chapter : XML Declaration.Document Elements SectionDocument Elements are the building blocks of XML. These divide the document into a hierarchy of sections, each serving a specific purpose. You can separate a document into multiple sections so that they can be rendered differently, or used by a search engine. The elements can be containers, with a combination of text and other elements.9You can learn more about XML elements in this chapter : XML Elements104.This chapter covers XML declaration in detail. XML declaration contains details that prepare an XML processor to parse the XML document. It is optional, but when used, it must appear in the first line of the XML document.SyntaxFollowing syntax shows XML declaration:Each parameter consists of a parameter name, an equals sign (=), and parameter value inside a quote. Following table shows the above syntax in detail:11RulesAn XML declaration should abide with the following rules:∙If the XML declaration is present in the XML, it must be placed as the first line in the XML document.∙If the XML declaration is included, it must contain version number attribute.∙The parameter names and values are case-sensitive.∙The names are always in lower case.∙The order of placing the parameters is important. The correct order is:version, encoding and standalone.∙Either single or double quotes may be used.∙The XML declaration has no closing tag, i.e. </?xml>XML Declaration ExamplesFollowing are few examples of XML declarations:XML declaration with no parameters:XML declaration with version definition:XML declaration with all parameters defined:XML declaration with all parameters defined in single quotes:125.Let us learn about one of the most important part of XML, the XML tags. XML tags form the foundation of XML. They define the scope of an element in XML. They can also be used to insert comments, declare settings required for parsing the environment, and to insert special instructions.We can broadly categorize XML tags as follows:Start T agThe beginning of every non-empty XML element is marked by a start-tag. Following is an example of start-tag:End T agEvery element that has a start tag should end with an end-tag. Following is an example of end-tag:Note, that the end tags include a solidus ("/") before the name of an element.Empty T agThe text that appears between start-tag and end-tag is called content. An element which has no content is termed as empty. An empty element can be represented in two ways as follows:A start-tag immediately followed by an end-tag as shown below:A complete empty-element tag is as shown below:Empty-element tags may be used for any element which has no content.13End of ebook previewIf you liked what you saw…Buy it from our store @ https://14。
TinyXml使用

这次使用了TinyXML后,觉得这个东西真是不错,于是将使用方法坐下总结来和大家分享。
该解析库在开源网站()上有下载,在本Blog也提供下载(下载TinyXML)TinyXML是一个开源的解析XML的解析库,能够用于C++,能够在Windows或Linux 中编译。
这个解析库的模型通过解析XML文件,然后在内存中生成DOM模型,从而让我们很方便的遍历这课XML树。
注:DOM模型即文档对象模型,是将整个文档分成多个元素(如书、章、节、段等),并利用树型结构表示这些元素之间的顺序关系以及嵌套包含关系(理解html语言的读者会很容易理解这种树状模型)。
如下是一个XML片段:<Persons><Person ID="1"><name>周星星</name><age>20</age></Person><Person ID="2"><name>白晶晶</name><age>18</age></Person></Persons>在TinyXML中,根据XML的各种元素来定义了一些类:TiXmlBase:整个TinyXML模型的基类。
TiXmlAttribute:对应于XML中的元素的属性。
TiXmlNode:对应于DOM结构中的节点。
TiXmlComment:对应于XML中的注释。
TiXmlDeclaration:对应于XML中的申明部分,即<?versiong="1.0" ?>。
TiXmlDocument:对应于XML的整个文档。
TiXmlElement:对应于XML的元素。
TiXmlText:对应于XML的文字部分。
TiXmlUnknown:对应于XML的未知部分。
TiXmlHandler:定义了针对XML的一些操作。
tinyxml使用笔记与总结

tinyxml使用笔记与总结tinyxml使用笔记与总结tinyxml使用笔记与总结在TinyXML中,根据XML的各种元素来定义了一些类:TiXmlBase:整个TinyXML模型的基类。
TiXmlAttribute:对应于XML中的元素的属性。
TiXmlNode:对应于DOM结构中的节点。
TiXmlComment:对应于XML中的注释。
TiXmlDeclaration:对应于XML中的申明部分,即<?versiong="1.0" ?>。
TiXmlDocument:对应于XML的整个文档。
TiXmlElement:对应于XML的元素。
TiXmlText:对应于XML的文字部分。
TiXmlUnknown:对应于XML的未知部分。
TiXmlHandler:定义了针对XML的一些操作。
例如:<?xml version="1.0" standalone=no><!– Our to do list data –><ToDo><Item priority="1"> Go to the <bold>Toy store!</bold></Item><Item priority="2"> Do bills</Item></ToDo> 整个对象树:TiXmlDocument "demo.xml"TiXmlDeclaration "version=’1.0′" "standalone=no"TiXmlComment " Our to do list data"TiXmlElement "ToDo"TiXmlElement "Item" Attribtutes: priority = 1TiXmlText "Go to the "TiXmlElement "bold"TiXmlText "Toy store!"TiXmlElement "Item" Attributes: priority=2TiXmlText "Do bills"在tinyXML中,用FirstChild("名字")查找节点时,调用FirstChild函数的节点与要查找的节点必须成“父子关系”。
TinyXML(TinyXPath) 使用总结

原来的Windows 平台下的项目使用了MSXML组件来访问Web Service 接口,后来因为跨平台的需要,在Linux平台下改用了GSOAP+TinyXML(TinyXPath)来完成所需功能。
使用TinyXPath还是遇到了一些问题,总结一下。
这里要说明一下TinyXPath是TinyXML+XPath,下载TinyXPath包的时候会包含TinyXML的原文件。
1. 使用XPath,来获取XML子节点TinyXpath所支持的XPath并不完整,而且缺少文档资料,试了一整天才试出来,直接把结果写下来1.)节点名大小写无关匹配这里要用到name函数和translate函数,首先转化所有的节点名到大写,然后再比较。
语法如下:*[translate(name(),'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')='XXXX']name函数返回节点名字,translate函数转换到大写。
2.)节点内容比较text函数返回节点内容,语法为*[text()='XXXX']3.)选择固定位置节点position函数用以指定第几个节点,语法为:*[position()=XXX] ,此处是数字类型举个例子,我们要选定节点名字为AAA,内容为BBB的第二个节点,XPath应改名为:*[translate(name(),'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')='AAA' and text()='BBB' and position()=2]这里还有个查询效率问题,并不确定把 position()=2 条件放在最前面是不是可以提高效率。
以上内容可以封装成一个函数:inline string getNodeXPath(const string & strNodeName, string strText="", string pos=""){string strVal;strVal += "*[";strVal += "translate(name(),'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ') = '"+ strNode Name + "'";if(!strText.empty())strVal +=" and text()= '" +strText+"'";if(!pos.empty())strVal +=" and position()= " +pos;strVal += "]";return strVal;}#define NODE(node) getNode(node)#define NODE_AT(node,pos) getNode(node,"",pos)4.) 查询子节点满足一定条件的节点没有看到TinyXPath提供的直接可以获取子节点内容的函数,这里使用变通的方法,即先判断子节点条件然后使用parent关键词指定返回父节点,定义了HAS_CHILD宏#define HAS_CHILD(node,txt)string(string("/")+getNode(node,txt)+string("/parent::*"))举个例子:string strXPath;strXPath= "/" + NODE("XMLDATA") + "/" + NODE("RATES") ;strXPath+= "/" + NODE("REPORATEVO")+HAS_CHILD("TERMBYYEAR",mStrType)+HAS_CHILD("CONTRACTDATE",mStrSubTyp e);strXPath+= "/" + NODE("RATE");多个HAS_CHILD之间是并列关系。
TinyXml使用指南

TinyXml使用指南一、 TinyXml的特点TinyXml是一个基于DOM模型的、非验证的轻量级C++解释器。
1. SAX和DOM目前XML的解析主要有两大模型:SAX和DOM。
其中SAX是基于事件的,其基本工作流程是分析XML文档,当发现了一个新的元素时,产生一个对应事件,并调用相应的用户处理函数。
这种方式占用内存少,速度快,但用户程序相应得会比较复杂。
而DOM(文档对象模型),则是在分析时,一次性的将整个XML文档进行分析,并在内存中形成对应的树结构,同时,向用户提供一系列的接口来访问和编辑该树结构。
这种方式占用内存大,速度往往慢于SAX,但可以给用户提供一个面向对象的访问接口,对用户更为友好。
2. 验证和非验证对于一个特定的XML文档而言,其正确性分为两个层次。
首先是其格式应该符合XML的基本格式要求,比如第一行要有声明,标签的嵌套层次必须前后一致等等,符合这些要求的文件,就是一个合格的XML文件,称作well-formatted。
但除此之外,一个XML文档因其内容的不同还必须在语义上符合相应的标准,这些标准由相应的DTD 文件或者Schema文件来定义,符合了这些定义要求的XML文件,称作valid。
因此,解析器也分为两种,一种是验证的,即会跟据XML文件中的声明,用相应的DTD文件对XML文件进行校验,检查它是否满足DTD文件的要求。
另一种是忽略DTD文件,只要基本格式正确,就可以进行解析。
就我所知,验证的解析器通常都是比较重量级的。
TinyXml不支持验证,但是体积很小,用在解析格式较为简单的XML文件,比如配置文件时,特别的合适。
二、 TinyXml的构建和使用1. 获取TinyXml首页在/tinyxml/index.html,从这里可以找到最新版本的源代码,目前的版本是2.3.4。
2.构建TinyXml在构建时可以选择是否支持STL,选择的话,则可以使用std::string,所以通常应该打开这个选项。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
TinyXML入门教程目录TinyXML入门教程 (1)什么是XML? (1)文档类 (2)创建文档对象 (3)输出文档对象 (3)保存文档对象 (4)返回第一个根元素 (5)声明类 (5)注释类 (6)元素类 (6)节点名 (6)父节点 (6)子节点 (7)编辑子节点 (7)同级节点 (7)遍历元素 (8)元素属性 (8)元素函数总结 (9)属性类 (10)什么是XML?XML全称EXtensible Markup Language,翻译为可扩展标记语言,简而言之就是你可以自定义数据的标识,以此来区分各种不同的数据,以便于进行数据交换,例如html就可以理解为一种简单的xml语言。
XML文件通常就是一个文本文件,可以使用任何编码。
上图就是我系统中一个xml文件的图标,使用VC2005打开它,你可以看到如下内容:XML也是有这几个对象组成了,一般来说我们经常使用的类如下:●TiXmlDocument:文档类,它代表了整个xml文件。
●TiXmlDeclaration:声明类,它表示文件的声明部分,如上图所示。
●TiXmlComment:注释类,它表示文件的注释部分,如上图所示。
●TiXmlElement:元素类,它是文件的主要部分,并且支持嵌套结构,一般使用这种结构来分类的存储信息,它可以包含属性类和文本类,如上图所示。
⏹TiXmlAttribute/TiXmlAttributeSet:元素属性,它一般嵌套在元素中,用于记录此元素的一些属性,如上图所示。
⏹TiXmlText:文本对象,它嵌套在某个元素内部,如上图所示。
TinyXml使用文档对象模型(DOM)来解析xml文件,这种模型的处理方式为在分析时,一次性的将整个XML文档进行分析,并在内存中形成对应的树结构,同时,向用户提供一系列的接口来访问和编辑该树结构。
这种方式占用内存大,但可以给用户提供一个面向对象的访问接口,对用户更为友好,非常方便用户使用。
下面我们依次来介绍各个类的用法。
文档类文档类代表一个XML文档,通过它,你可以保存,载入和打印输出文档。
你可以通过以下方式载入xml文档到TiXmlDocument。
创建文档对象●创建一个空的文档对象,然后载入一个xml文档使用到的函数原形如下:+TiXmlDocument();+bool LoadFile( const std::string& filename)在程序中你可以如下使用:●2、在构造函数中传入文档的名称,然后调用load函数完成解析载入使用到的函数原形如下:+TiXmlDocument( const std::string& documentName );+bool LoadFile();在程序中你可以如下使用:输出文档对象文档类提供了Print()函数用于在控制台输出当前的文档内容,这个函数的原形如下:+void Print() const在程序中你可以如下使用:tutorial.xml的内容如下:在控制台中你可以得到如下输出:由于文件使用UTF-8编码,而Windows下的控制台默认使用gb2312编码,因此会生成乱码。
保存文档对象当然你也可以使用SaveFile()函数来进行另存为,这个函数的原形如下:bool SaveFile( const std::string& filename ) const在程序中你可以如下使用:返回第一个根元素另外文档对象还提供了一个实用的函数用于返回第一个根对象,它可以让你方便的遍历整个文档结构,查找自己需要的数据。
函数原形如下:+TiXmlElement* RootElement()我们在介绍元素类的时候再详细介绍它的使用。
声明类在标准的XML文件中,声明为文件的第一项,例如<?xml version="1.0" standalone="yes"?>,声明对象具有三个属性值,版本,编码和独立文件声明一般来说文档的第一行就是声明对象,你可以把文档对象的第一个子节点转换为声明对象。
+const char *Version() const+const char *Encoding() const+const char *Standalone() const在程序中你可以如下使用:注释类这个类一般为xml数据提供解释说明,在程序中一般不使用它,因此,这里就不介绍了。
元素类元素为一个容器类,它具有元素名称,并可以包含其它元素,文本,注释和未知节点,这些对象统称为元素的节点,即节点可以为元素、文本、注释和未知节点类型。
元素也可以包含任意个数的属性。
节点名在上方元素的代码中,element为根元素的名称,你可以通过如下的函数来设置和返回它。
+const std::string& ValueStr() const+void SetValue( const std::string& _value )父节点subelement1,subelement2,subelement3,subelement4都是element的子元素,如果当前元素对象的指针指向subelement1,subelement2,subelement3,subelement4,你可以通过Parent()函数来返回指向element对象的指针,Parent()函数的声明如下:+TiXmlNode* Parent()子节点通过父节点的指针,你可以遍历所有的子节点。
+TiXmlNode* FirstChild()+TiXmlNode* FirstChild( const std::string& _value )上面两个函数用于返回第一个子节点对象的指针,带参数名的那个函数表示返回第一个名为_value的子节点。
+TiXmlNode* LastChild()+TiXmlNode* LastChild( const std::string& _value )上面的两个函数用于返回最后一个节点对象的指针,带参数名的那个函数表示返回最后一个名为_value的子节点。
你也可以使用IterateChildren()函数来依次遍历所有的节点,它们的函数声明如下:+TiXmlNode* IterateChildren( const TiXmlNode* previous )+TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous )带参数名的那个函数表示只遍历同名的节点。
编辑子节点你可以插入、删除替换所有的子节点。
+TiXmlNode* InsertEndChild( const TiXmlNode& addThis );+TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis );+TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis );上面三个函数用于插入节点,InsertEndChild函数让你把新节点插入到末尾,InsertBeforeChild 和InsertAfterChild函数允许你在指定的节点位置前后插入节点。
+TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); ReplaceChild函数用于替换指定的节点。
+bool RemoveChild( TiXmlNode* removeThis );RemoveChild函数让你删除指定的节点。
void Clear();Clear函数会删除本节点的所有子节点(包括子节点包含的从子节点),但不会修改本节点。
同级节点subelement1、subelement2、subelement3、subelement4我们也提供了相关的函数用于在这些同级节点中遍历。
+TiXmlNode* PreviousSibling()+TiXmlNode* PreviousSibling( const std::string& _value )可以根据当前的节点,返回上一个节点的指针。
带参数名的那个函数表示返回上一个名为_value的节点。
当然你也可以根据当前的节点,返回下一个节点的指针。
带参数名的那个函数表示返回下一个名为_value的节点。
+TiXmlNode* NextSibling()+TiXmlNode* NextSibling( const std::string& _value)遍历元素元素是一种特殊的节点,以’<’为开始字符,后接元素名称。
函数NextSiblingElement用于返回下一个同级元素,而忽略其它类型的节点。
它们的函数声明如下:+TiXmlElement* NextSiblingElement()+TiXmlElement* NextSiblingElement( const std::string& _value)带参数名的那个函数表示返回下一个名为_value的同级元素。
本类也提供了相关的函数,让你返回第一个子元素。
+TiXmlElement* FirstChildElement()+TiXmlElement* FirstChildElement( const std::string& _value )带参数名的那个函数表示返回下一个名为_value的子元素。
元素属性属性一般保存在元素中,它们为使用“=”号连接的两个字符串,左边的表示属性名,等号右边的表示属性值,通常使用字符串、整数和浮点数等数据类型表示。
例如,pi = 3.14。
你可以通过如下的函数,返回属性值。
+const std::string* Attribute( const std::string& name ) const;+const std::string* Attribute( const std::string& name, int* i ) const;+const std::string* Attribute( const std::string& name, double* d ) const;在上面3个函数中,第一个函数使用字符串保存返回的属性值,第二个函数把属性值转换为整数然后返回,第三个函数把属性值转换为浮点数然后返回。