TinyXML入门教程
- 格式:docx
- 大小:140.06 KB
- 文档页数:10
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查找唯一节点及修改节点操作分类: 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>它也是没有孩子节点的。
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后,觉得这个东西真是不错,于是将使用方法坐下总结来和大家分享。
该解析库在开源网站()上有下载,在本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中,根据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函数的节点与要查找的节点必须成“父子关系”。
原来的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是一个基于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,所以通常应该打开这个选项。
TinyXML 指南这是什么?这份指南有一些关于如何有效地使用TinyXML的技巧和建议。
我也会尝试讲一些诸如怎样使字符串与整型数相互转化的C++技巧。
这与TinyXML本身没什么关系,但它也许会对你的项目有所帮助,所以我还是把它加进来了。
如果你不知道基本的C++概念,那么这份指南就没什么用了。
同样的,如果你不知道什么是DOM,那先从其它地方找来看看吧。
在我们开始之前一些将会被用到的XML数据集/文件。
example1.xml:<?xml version="1.0" ?><Hello>World</Hello>example2.xml:<?xml version="1.0" ?><poetry><verse>AlasGreat WorldAlas (again)</verse></poetry>example3.xml:<?xml version="1.0" ?><shapes><circle name="int-based" x="20" y="30" r="50" /><point name="float-based" x="3.5" y="52.1" /></shapes>example4.xml:<?xml version="1.0" ?><MyApp><!–Settings for MyApp –><Messages><Welcome>Welcome to MyApp</Welcome><Farewell>Thank you for using MyApp</Farewell></Messages><Windows><Window name="MainFrame" x="5" y="15" w="400" h="250" /></Windows><Connection ip="192.168.0.1" timeout="123.456000" /></MyApp>开始把文件加载成XML把一个文件加载成TinyXML DOM的最简单方法是:TiXmlDocument doc( "demo.xml" );doc.LoadFile();一个更接近于现实应用的例子如下。
Linux下TinyXml库使⽤⽅法及实例解析 TinyXml库下载,我保存在⾃⼰的⽹盘中,可⾃⾏下载:链接:提取码:e50y⾸先介绍⼀下TinyXml类XmlBase:整个TinyXML模型的基类;XmlAttribute:对应于XML中的元素的属性;XmlComment:对应于XML中的注释,评论类;XmlDeclaration:对应于XML中的申明部分,即<?versiong="1.0" ?>;XmlElement:对应于XML的元素;XmlDocument:对应于XML的整个⽂档;XmlText:对应于XML的⽂字部分;XmlUnknown:对应于XML的未知部分;XmlHandler:定义了针对XML的⼀些操作;类之间的关系如下:需要注意的是:元素⼀定的节点,节点不⼀定是元素(TiXmlElement类)⼀.加载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下⾯介绍⼀个实例解析使⽤TinyXML库进⾏解析时,只需要将其中的6个⽂件拷贝到项⽬中就可以直接使⽤了,这六个⽂件是:tinyxml.h、tinystr.h、tinystr.cpp、tinyxml.cpp、tinyxmlerror.cpp、tinyxmlparser.cpp;XML⽂件如下---test.xml1 <School name="软件学院">2 <Class name = "C++">3 <Student name="tinyxml" number="123">4 <email>tinyxml@</email>5 <address>中国</address>6 </Student>7 <Student name="jsoncpp" number="456">8 <email>jsoncpp@</email>9 <address>美国</address>10 </Student>1112 </Class>1314 </School>~解析实例代码为:readxml.cpp1 #include<iostream>2 #include"tinyxml.h"3 #include<string>45using namespace std;67int main()8 {9const char * xmlFile = "test.xml";10 TiXmlDocument doc;11if(doc.LoadFile(xmlFile)){12 doc.Print();13 }else{14 cout << "can not parse xml school" << endl;1516 }17 TiXmlElement* rootElement = doc.RootElement();18 TiXmlElement* classElement = rootElement->FirstChildElement();19 TiXmlElement* studentElement = classElement->FirstChildElement();2021for(; studentElement != NULL; studentElement = studentElement->NextSiblingElement()){22 TiXmlAttribute* attribute0fStudent = studentElement->FirstAttribute();23for(; attribute0fStudent != NULL; attribute0fStudent = attribute0fStudent->Next()){24 cout << attribute0fStudent->Name() << " : " << attribute0fStudent->Value() << endl ;25 }26 TiXmlElement* studentContactElement = studentElement->FirstChildElement();27for(; studentContactElement != NULL; studentContactElement = studentContactElement->Ne xtSiblingElement()){28string contactType = studentContactElement->Value();29string contactValue = studentContactElement->GetText();30 cout << contactType << " : " << contactValue << endl;31 }32 }33return0;34 }35~如下为我⼯程下的⽂件csc105@csc105:~/workspace/configure-the-lower-computer/zmqcore/test_t/template/tinyxml$ lsreadxml test.xml tinystr.h tinyxmlerror.cpp tinyxmlparser.cppreadxml.cpp tinystr.cpp tinyxml.cpp tinyxml.h运⾏执⾏⽂件,解析结果为:csc105@csc105:~/workspace/configure-the-lower-computer/zmqcore/test_t/template/tinyxml$ ./readxml <School name="软件学院"><Class name="C++"><Student name="tinyxml" number="123"><email>tinyxml@</email><address>中国</address></Student><Student name="jsoncpp" number="456"><email>jsoncpp@</email><address>美国</address></Student></Class></School>name : tinyxmlnumber : 123email : tinyxml@address : 中国name : jsoncppnumber : 456email : jsoncpp@address : 美国到此,完成了XML 实例的解析最后感谢原博主:https:///qq_26374395/article/details/80171906。
开源TinyXML最简单的新⼿教程TinyXML它是基于⼀个⾮常受欢迎的现在DOM型号XML解析器,简单易⽤且⼩巧玲珑,很适合存储简单数据。
配置⽂件。
该项⽬属于开源项⽬,在sourceforge上边的链接是:当前最新版本号是2.6.2先看⼀下源代码⽂档的结构:Docs是帮助⽂档。
⾥边有许多的使⽤说明,只截⼀张图看⼀下:详细依据须要再看我们使⽤的是它的库。
能够是静态的也能够是动态库。
我就⽤静态库了,将这⾥边的⼏个头⽂件和源⽂件⼀起创建⼀个project,⽣成Lib库:tinyxml.lib使⽤的时候,将这两个头⽂件以及⽣成的静态库加进去:⼀个简单的样例#include <iostream>using namespace std;#ifdef TIXML_USE_STL#include <iostream>#include <sstream>using namespace std;#else#include <stdio.h>#endif#if defined( WIN32 ) && defined( TUNE )#include <crtdbg.h>_CrtMemState startMemState;_CrtMemState endMemState;#endif#include "tinyxml/tinyxml.h"int main(){TiXmlDocument *pDoc = new TiXmlDocument;if (NULL==pDoc){return false;}TiXmlDeclaration *pDeclaration = new TiXmlDeclaration("1.0","gb2312","");if (NULL==pDeclaration){return false;}pDoc->LinkEndChild(pDeclaration);// ⽣成⼀个根节点TiXmlElement *pRootEle = new TiXmlElement("索引数据包信息");pDoc->LinkEndChild(pRootEle);//头节点TiXmlElement *pHeader = new TiXmlElement("头节点");pRootEle->LinkEndChild(pHeader);TiXmlElement *pCellNode = new TiXmlElement("字段1");pHeader->LinkEndChild(pCellNode);pCellNode->SetAttribute("str1","1状态");pCellNode->SetAttribute("str2","0状态");pDoc->SaveFile("d:\\result.xml");return 0;}结果:临时这⾥边的字符串不能是宽字符的。
tinyxml使用文档TinyXML是一个用于解析和生成XML文档的C++库。
它提供了简单而高效的API,使得在C++中处理XML变得容易。
本文将介绍TinyXML的基本使用方法,包括XML的解析、创建和修改。
1. 引入TinyXML库2.解析XML文档要解析XML文档,可以使用TinyXML提供的XMLDocument类。
首先,需要创建一个XMLDocument对象,并通过调用其LoadFile(方法加载XML 文件。
以下是一个解析XML文档的示例:```cpp#include "tinyxml.h"int mainTiXmlDocument doc;if (doc.LoadFile("example.xml"))TiXmlElement* root = doc.RootElement(;if (root)//处理根元素//...}}return 0;```在上面的示例中,首先创建一个XMLDocument对象,并通过调用LoadFile(方法加载名为"example.xml"的XML文件。
然后,通过调用RootElement(方法获取根元素,并进行进一步处理。
3.遍历XML元素要遍历XML元素,可以使用TiXmlElement类的NextSiblingElement(和FirstChildElement(方法。
NextSiblingElement(方法返回下一个同级元素,而FirstChildElement(方法返回第一个子元素。
以下是一个遍历XML元素的示例:```cppTiXmlElement* element = root->FirstChildElement(;while (element)//处理元素//...element = element->NextSiblingElement(;```在上面的示例中,首先通过调用FirstChildElement(方法获取第一个子元素,然后使用一个循环遍历所有同级元素。
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也是有这几个对象组成了,一般来说我们经常使用的类如下:l TiXmlDocument:文档类,它代表了整个xml文件。
l TiXmlDeclaration:声明类,它表示文件的声明部分,如上图所示。
l TiXmlComment:注释类,它表示文件的注释部分,如上图所示。
l TiXmlElement:元素类,它是文件的主要部分,并且支持嵌套结构,一般使用这种结构来分类的存储信息,它可以包含属性类和文本类,如上图所示。
n TiXmlAttribute/TiXmlAttributeSet:元素属性,它一般嵌套在元素中,用于记录此元素的一些属性,如上图所示。
n TiXmlText:文本对象,它嵌套在某个元素内部,如上图所示。
TinyXml使用文档对象模型(DOM)来解析xml文件,这种模型的处理方式为在分析时,一次性的将整个XML文档进行分析,并在内存中形成对应的树结构,同时,向用户提供一系列的接口来访问和编辑该树结构。
这种方式占用内存大,但可以给用户提供一个面向对象的访问接口,对用户更为友好,非常方便用户使用。
下面我们依次来介绍各个类的用法。
文档类文档类代表一个XML文档,通过它,你可以保存,载入和打印输出文档。
TinyXml使用说明1. 安装和引入TinyXml库2.创建XML文档使用TinyXml,你可以创建一个XML文档对象。
首先,包含头文件`tinyxml.h`。
```cpp#include "tinyxml.h"```然后,通过使用 `TiXmlDocument` 类来创建一个XML文档对象。
```cppTiXmlDocument doc;```3.加载和保存XML文档一旦你创建了一个XML文档对象,你就可以加载一个XML文件或字符串,并将其保存为XML文件。
-加载XML文件:```cppbool loadSuccess = doc.LoadFile("example.xml");if (loadSuccess)//文件加载成功,可以对其进行处理} else//文件加载失败,进行错误处理}```-加载XML字符串:```cppconst char* xmlString ="<root><element>value</element></root>";bool loadSuccess = doc.Parse(xmlString);if (loadSuccess)//字符串解析成功,可以对其进行处理} else//字符串解析失败,进行错误处理}```-保存XML文档:```cppdoc.SaveFile("output.xml");```4.获取XML元素使用TinyXml,你可以获取XML文档中的元素和属性。
首先,你需要获取XML文档的根元素。
```cppTiXmlElement* root = doc.RootElement(;```接下来,你可以使用 `TiXmlElement` 类的成员函数来获取元素的名称、值和属性。
-获取元素的名称和值:```cppconst char* elementName = root->Value(;const char* elementValue = root->GetText(;```-获取元素的属性:```cppconst char* attributeName = root->Attribute("name");```5.遍历XML元素使用TinyXml,你可以遍历XML文档中的元素和属性,并对其进行处理。
TinyXML解析TinyXML介绍最近做⼀个负载均衡的⼩项⽬,需要解析xml配置⽂件,⽤到了TinyXML,感觉使⽤起来很容易,给出⼀个使⽤TinyXML进⾏XML解析的简单例⼦,很多复杂的应⽤都可以基于本例⼦的⽅法来完成。
TinyXML是⼀个开源的解析XML的解析库,能够⽤于C++,能够在Windows或Linux中编译。
这个解析库的模型通过解析XML⽂件,然后在内存中⽣成DOM模型,从⽽让我们很⽅便的遍历这棵XML树。
DOM模型即⽂档对象模型,是将整个⽂档分成多个元素(如书、章、节、段等),并利⽤树型结构表⽰这些元素之间的顺序关系以及嵌套包含关系。
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的⼀些操作。
下载和编译⼯作⽬录为:tinyxml/ //⼯作⽬录|-- include //头⽂件根⽬录| |-- tinyxml //tinyxml头⽂件,包括tinystr.h tinyxml.h|-- src //cpp源码⽂件根⽬录 |-- tinyxml //tinyxml源码⽂件夹,包括tinystr.cpp tinyxml.cpp tinyxmlerror.cpp tinyxmlparser.cpp |-- main.cpp //我们的主函数,调⽤tinyxml的⽰例代码|-- conf //我们⽰例中⽤的xml⽂件所在的⽂件夹|-- makefile //makefile,不⽤我们多说了吧,不懂请看我博客的makefile最佳实践简单的例⼦在conf⽬录下建⽴student.xml代码<School name="软件学院"><Class name = "C++"><Student name="tinyxml" number="123"><email>tinyxml@</email><address>中国</address></Student><Student name="jsoncpp" number="456"><email>jsoncpp@</email><address>美国</address></Student></Class></School>想要使⽤tinyxml,只需要在头⽂件中包含<tinyxml.h>即可读取整个xml⽂件并打印代码:void printSchoolXml() {using namespace std;TiXmlDocument doc;const char * xmlFile = "conf/school.xml";if (doc.LoadFile(xmlFile)) {doc.Print();} else {cout << "can not parse xml conf/school.xml" << endl;}}读取XMLvoid readSchoolXml() {using namespace std;const char * xmlFile = "conf/school.xml";TiXmlDocument doc;if (doc.LoadFile(xmlFile)) {doc.Print();} else {cout << "can not parse xml conf/school.xml" << endl;return;}TiXmlElement* rootElement = doc.RootElement(); //School元素TiXmlElement* classElement = rootElement->FirstChildElement(); // Class元素TiXmlElement* studentElement = classElement->FirstChildElement(); //Studentsfor (; studentElement != NULL; studentElement = studentElement->NextSiblingElement() ) {TiXmlAttribute* attributeOfStudent = studentElement->FirstAttribute(); //获得student的name属性for (;attributeOfStudent != NULL; attributeOfStudent = attributeOfStudent->Next() ) {cout << attributeOfStudent->Name() << " : " << attributeOfStudent->Value() << std::endl;}TiXmlElement* studentContactElement = studentElement->FirstChildElement();//获得student的第⼀个联系⽅式for (; studentContactElement != NULL; studentContactElement = studentContactElement->NextSiblingElement() ) { string contactType = studentContactElement->Value();string contactValue = studentContactElement->GetText();cout << contactType << " : " << contactValue << std::endl;}}}写⼊xmlvoid 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@") );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@"));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节点上移除⼦节点BTiXmlNode 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节点,获取第⼀个属性值。
C++使用TinyXML解析XML先下载TinyXML,百度一下就行,下载下来解压,里面有2个头文件和4个cpp文件,一起加到工程里面,如图所示xmldemo.cpp是包含主函数的文件,下面直接上代码,很简单,不管怎么样,总算是实现了,虽然题目要求不使用外加类库实现,过段时间等题解出来我再上来更新不加外库实现的方法。
<School name="软件学院"><Class name= "C++"><Student name="tinyxml"number="123"><email>tinyxml@</email><address>中国</address></Student><Student name="jsoncpp"number="456"><email>jsoncpp@</email><address>美国</address></Student></Class></School>以上是要读取xml文件,下面的是xmlTest.cpp。
#include <iostream>#include "tinystr.h"#include "tinyxml.h"#include <string>using namespace std;void readSchoolXml() {using namespace std;const char* xmlFile = "school.xml";TiXmlDocumentdoc;if(doc.LoadFile(xmlFile)) {doc.Print();} else{cout << "can not parse school.xml"<< endl;return;}TiXmlElement* rootElement = doc.RootElement(); //School元素TiXmlElement* classElement =rootElement->FirstChildElement(); // Class元素TiXmlElement* studentElement =classElement->FirstChildElement(); //Studentsfor(; studentElement != NULL; studentElement = studentElement->NextSiblingElement() ) {TiXmlAttribute* attributeOfStudent =studentElement->FirstAttribute(); //获得student的name属性for(;attributeOfStudent != NULL; attributeOfStudent = attributeOfStudent->Next() ) {cout << attributeOfStudent->Name() << " : "<< attributeOfStudent->Value() << std::endl;}TiXmlElement* studentContactElement =studentElement->FirstChildElement();//获得student的第一个联系方式for(; studentContactElement != NULL; studentContactElement = studentContactElement->NextSiblingElement() ) {string contactType =studentContactElement->Value();string contactValue =studentContactElement->GetText();cout << contactType << " : "<< contactValue << std::endl;}}int main(){readSchoolXml();system("pause");return1;}运行结果界面:。
C++通过TinyXML类库读写XML⽂件TinyXML是⼀个开源的解析XML的解析库,能够⽤于C++,能够在Windows或中编译。
这个解析库的模型通过解析XML⽂件,然后在内存中⽣成DOM模型,从⽽让我们很⽅便的遍历这棵XML树。
DOM模型即⽂档对象模型,是将整个⽂档分成多个元素(如书、章、节、段等),并利⽤树型结构表⽰这些元素之间的顺序关系以及嵌套包含关系。
使⽤之前,需要先下载TinyXML类库:。
也可在sourceforge上下载:。
然后解压缩TinyXML后,将这六个⽂件添加到你的c++⼯程中,分别是tinystr.h、tinystr.cpp、tinyxml.h、tinyxml.cpp、tinyxmlerror.cpp、tinyxmlparser.cpp。
如本⽰例中,只有 main.cpp 才是代码:编写代码时,只需要包含 tinyxml.h 头⽂件即可,但是,编译时却需要把所有.cpp ⽂件都加上。
⽰例代码如下:[cpp]1. #include <stdio.h>2. #include "tinyxml.h"3. #include <iostream>4. #include <cstring>5. using namespace std;6.7. /*8. TiXmlDocument:⽂档类,它代表了整个xml⽂件9. TiXmlDeclaration:声明类,它表⽰⽂件的声明部分10. TiXmlComment:注释类,它表⽰⽂件的注释部分11. TiXmlElement:元素类,它是⽂件的主要部分,并且⽀持嵌套结构,⼀般使⽤这种结构来分类的存储信息,它可以包含属性类和⽂本类12. TiXmlAttribute/TiXmlAttributeSet:元素属性,它⼀般嵌套在元素中,⽤于记录此元素的⼀些属性13. TiXmlText:⽂本对象,它嵌套在某个元素内部14. */15. //创建xml⽂件16. int writeXmlFile()17. {18. TiXmlDocument *writeDoc = new TiXmlDocument; //xml⽂档指针19.20. //⽂档格式声明21. TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "UTF-8", "yes");22. writeDoc->LinkEndChild(decl); //写⼊⽂档23.24. int n = 3; //⽗节点个数25.26. TiXmlElement *RootElement = new TiXmlElement("Info");//根元素27. RootElement->SetAttribute("num", n); //属性28. writeDoc->LinkEndChild(RootElement);29.30. for(int i=0; i<n; i++)//n个⽗节点31. {32. TiXmlElement *StuElement = new TiXmlElement("Stu");//Stu33. //设置属性34. StuElement->SetAttribute("class","A");35. if(2 == i)36. {37. StuElement->SetAttribute("class","B");38. }39.40. StuElement->SetAttribute("id",i+1);41. StuElement->SetAttribute("flag", (i+1)*10);42. RootElement->LinkEndChild(StuElement);//⽗节点写⼊⽂档43.44. //姓名45. TiXmlElement *nameElement = new TiXmlElement("name");46. StuElement->LinkEndChild(nameElement);47.48. TiXmlText *nameContent = new TiXmlText("mike");49. nameElement->LinkEndChild(nameContent);50.51. //分数52. TiXmlElement *scoreElement = new TiXmlElement("score");53. StuElement->LinkEndChild(scoreElement);54.55. TiXmlText *scoreContent = new TiXmlText("88");56. scoreElement->LinkEndChild(scoreContent);57.58. //城市59. TiXmlElement *cityElement = new TiXmlElement("city");60. StuElement->LinkEndChild(cityElement);61.62. TiXmlText *cityContent = new TiXmlText("Shenzhen");63. cityElement->LinkEndChild(cityContent);64.65. }66.67. writeDoc->SaveFile("stu_info.xml");68. delete writeDoc;69.70. return 1;71. }72.73. //解析xml⽂件74. int readXmlFile()75. {76. TiXmlDocument mydoc("stu_info.xml");//xml⽂档对象77. bool loadOk=mydoc.LoadFile();//加载⽂档78. if(!loadOk)79. {80. cout<<"could not load the test file.Error:"<<mydoc.ErrorDesc()<<endl;81. exit(1);82. }83.84. TiXmlElement *RootElement=mydoc.RootElement(); //根元素, Info85. cout<< "[root name]" << RootElement->Value() <<"\n";86.87. TiXmlElement *pEle=RootElement;88.89. //遍历该结点90. for(TiXmlElement *StuElement = pEle->FirstChildElement();//第⼀个⼦元素91. StuElement != NULL;92. StuElement = StuElement->NextSiblingElement())//下⼀个兄弟元素93. {94. // StuElement->Value() 节点名称95. cout<< StuElement->Value() <<" ";96. TiXmlAttribute *pAttr=StuElement->FirstAttribute();//第⼀个属性97.98. while( NULL != pAttr) //输出所有属性99. {100. cout<<pAttr->Name()<<":"<<pAttr->Value()<<" ";101. pAttr=pAttr->Next();102. }103. cout<<endl;104.105. //输出⼦元素的值106. for(TiXmlElement *sonElement=StuElement->FirstChildElement(); 107. sonElement;108. sonElement=sonElement->NextSiblingElement())109. {110. cout<<sonElement->FirstChild()->Value()<<endl;111. }112. }113.114. return 1;115. }116.117. int main(int argc, char *argv[])118. {119.120. writeXmlFile();121. printf("\nafter write\n");122.123. readXmlFile();124.125. return 0;126. }编译运⾏结果如下:⽣成的xml⽂件内容如下:[html]1. <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>2. <Info num="3">3. <Stu class="A" id="1" flag="10">4. <name>mike</name>5. <score>88</score>6. <city>Shenzhen</city>7. </Stu>8. <Stu class="A" id="2" flag="20">9. <name>mike</name>10. <score>88</score>11. <city>Shenzhen</city>12. </Stu>13. <Stu class="B" id="3" flag="30">14. <name>mike</name>15. <score>88</score>16. <city>Shenzhen</city>17. </Stu>18. </Info>本教程⽰例代码下载请点此链接:。
TinyXML2使用教程一、TinyXML2的安装```$ make```编译完成后,会在当前目录下生成一个名为libtinyxml2.a的库文件,将其复制到您的开发环境中的库文件夹中即可。
二、读取XML文件在开始使用TinyXML2进行读取XML文件之前,需要在您的代码中包含TinyXML2的头文件:```#include <tinyxml2.h>```要读取一个XML文件,首先需要创建一个XML文档对象,并调用它的LoadFile(方法来加载XML文件:```tinyxml2::XMLDocument doc;doc.LoadFile("example.xml");```如果加载成功,可以通过调用根节点的FirstChildElement(方法来获取XML文件的根元素:```tinyxml2::XMLElement* root = doc.FirstChildElement("root");```然后可以使用root指针来访问根元素的属性和子元素:```const char* rootValue = root->GetText(; // 获取根元素的文本值tinyxml2::XMLElement* child = root->FirstChildElement("child"); // 获取根元素的名为"child"的第一个子元素const char* childValue = child->GetText(; // 获取子元素的文本值```还可以使用循环来遍历根元素的所有子元素:```for (tinyxml2::XMLElement* child = root->FirstChildElement(; child; child = child->NextSiblingElement()const char* childName = child->Name(; // 获取子元素的名称const char* childValue = child->GetText(; // 获取子元素的文本值}```三、修改XML文件使用TinyXML2库可以很方便地修改XML文件。
(转)XML解析器(TinyXML)的使⽤1.⾸先下载TinyXML库的⽂件,这⾥给出链接/tinyxml/tinyxml_2_3_4.zip?download2.下载后解压这个压缩包,把所有的东西放到⼀个找的着的地⽅(⽐如,E:\开发库\TinyXML)3.⽤Visual C++(推荐VC++.NET2003)创建⼀个新的⼯程(Win32控制台)4.在TinyXML的⽬录⾥⾯找到tinystr.h, tinyxml.h, tinystr.cpp, tinyxml.cpp, tinyxmlerror.cpp, tinyxmlparser.cpp六个⽂件加⼊到刚刚创建的项⽬中去5.打开tinyxml.h, 在第⼀⾏加⼊下⾯这⾏:#define TIXML_USE_STL //标志使⽤STL的内容6.然后创建⼀个cpp⽂件,输⼊下⾯的内容:#include<iostream>#include<fstream>#include"tinyxml.h"using namespace std;int_tmain(int argc, _TCHAR* argv[]){//原先代码是直接加载XML⽂件,我作了⼀下修改,把内容读到字符串后再解析,实际使⽤时就去掉读取XML⽂件这⼀步string filename = "first.xml";//TiXmlDocument* doc = new TiXmlDocument(filename.c_str());////////////////////////////////////////////////////////////////////////////在这⾥复制⽂件//////////////////////////////////////////////////////////////////////////std::ifstream ifs(filename.c_str());char buffer[1024];char c, *p = buffer;while(ifs.get(c)){*p++=c;}*p = 0;ifs.close();////////////////////////////////////////////////////////////////////////////这⾥开始从字符串中解析XML//创建TiXmlDocument对象TiXmlDocument* doc = new TiXmlDocument();//解析if(!doc->Parse(buffer)){cout << doc->ErrorDesc() << endl;}//获取根节点const TiXmlElement* root = doc->RootElement();//循环获取该根节点下⾯的节点for( const TiXmlNode* child = root->FirstChild();child;child=child->NextSibling()){//判断为元素类型并且是staticbox元素,Value()获取该标签的名称if((child->Type() == TiXmlNode::ELEMENT) && (!strcmp(child->Value(),"staticbox"))){const TiXmlElement *box = (const TiXmlElement*)child;double px, py, pz;double dx, dy, dz;//获取属性值std::string mesh;mesh = box->Attribute("mesh");//继续循环获取⼦节点相关数据for(const TiXmlNode *sub_tag = box->FirstChild(); sub_tag; sub_tag = sub_tag->NextSibling() ){if(sub_tag->Type() == TiXmlNode::ELEMENT){const TiXmlElement *sub_element = (const TiXmlElement*)sub_tag;if(!strcmp(sub_tag->Value(),"position")){px = (sub_element->Attribute("x",&px))?px:0.0;py = (sub_element->Attribute("y",&py))?py:0.0;pz = (sub_element->Attribute("z",&pz))?pz:0.0;}else if(!strcmp(sub_tag->Value(),"dimension")){dx = (sub_element->Attribute("x",&dx))?dx:1.0;dy = (sub_element->Attribute("y",&dy))?dy:1.0;dz = (sub_element->Attribute("z",&dz))?dz:1.0;}else if(!strcmp(sub_tag->Value(),"test")){//使⽤GetText()⽅法来获取该标签的值,如这⾥获取的是test的值1和2//string temp = sub_element->GetText();这⾥有些错,所以注释去}}}cout << "<StaticBox>\n";cout << "\tPosition = (" << px << ", " << py << ", " << pz << ")\n";cout << "\tDimension = (" << dx << ", " << dy << ", " << dz << ")\n\n"; }}delete doc;getchar();return 0;}7.然后在项⽬的⽂件夹中加⼊⼀个xml⽂件,取名为first.xml,如下: <?xml version="1.0" encoding="utf-8" ?><Scene><staticbox mesh="crate.mesh"><position x="-8" y="2" z="4" /><dimension x="2" y="4" z="2" /><test>1</test></staticbox><staticbox mesh="crate.mesh"><position x="3" y="2" z="4" /><dimension x="2" y="4" z="2" /><test>2</test></staticbox></Scene>8.编译运⾏。
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个函数中,第一个函数使用字符串保存返回的属性值,第二个函数把属性值转换为整数然后返回,第三个函数把属性值转换为浮点数然后返回。