Chinaunix首页 | 论坛 | 博客
  • 博客访问: 198843
  • 博文数量: 69
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 720
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-03 11:35
文章分类

全部博文(69)

文章存档

2011年(13)

2010年(46)

2009年(10)

我的朋友

分类:

2010-01-20 10:00:37

tinyXML100120:tinyXML备忘

@ http://zcatt.cublog.cn
tinyXML是一个小巧实用的xml解析工具,简简单单的,由两个头文件和四个cpp文件组成,直接用在自己的代码中或者生成库使用都很方便。tinyXML是采用top-down的方式解析xml,简洁明了。当然tinyXML的个头也决定了它的功能有限,例如不支持DTD&XSL,但应付简单场景也就足够了。
 
按照DOM的思想,xml被看成各个节点(元素)的嵌套和排列,TiXmlNode是节点基类,由此派生出TiXmlDocument,代表整个xml文档;TiXmlComment,TiXmlDeclaration,TiXmlElement,TiXmlText,和TiXmlUnknow是各种节点的类。
              TiXmlNode
                     TiXmlComment
                     TiXmlDeclaration
                     TiXmlDocument
                     TiXmlElement
                     TiXmlText
                     TiXmlUnknow
节点的属性(attribute)则用TiXmlAttribute来表示。
特别一提的是TiXmlHandle类,它的引入是专门为了解决累赘的空指针检查问题的。下面粘贴的是tinyXML文档中的一段解释。

A TiXmlHandle is a class that wraps a node pointer with null checks; this is an incredibly useful thing.

Note that TiXmlHandle is not part of the TinyXml DOM structure. It is a separate utility class.

Take an example:
       

              

                      

                      

              
       
       

Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very easy to write a *lot* of code that looks like:

        TiXmlElement* root = document.FirstChildElement( "Document" );

        if ( root )
        {

               TiXmlElement* element = root->FirstChildElement( "Element" );

               if ( element )

               {

                       TiXmlElement* child = element->FirstChildElement( "Child" );

                       if ( child )

                       {

                               TiXmlElement* child2 = child->NextSiblingElement( "Child" );

                               if ( child2 )

                               {

                                      // Finally do something useful.

       

And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity of such code. A TiXmlHandle checks for null pointers so it is perfectly safe and correct to use:

        TiXmlHandle docHandle( &document );

        TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).ToElement();

        if ( child2 )

        {

               // do something useful

       
Which is MUCH more concise and useful.
 
 
 
 
 
 
 
 
Locations of visitors to this page
阅读(1235) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~