C++使用tinyxml来操作DOM对象(以svg格式为例,其他格式都类似操作)

来源:互联网 发布:软件开发质量考核指标 编辑:程序博客网 时间:2024/05/29 13:19

1.首先去下载tinyxml库,在这里下载http://sourceforge.net/projects/tinyxml/   。我使用tinyxml作为例子,不用tinyxml2。下载完毕后将两个头文件tinystr.h和tinyxml.h放到工程的头文件下,并包含进工程。然后将四个.c文件tinystr.c ,tinyxml.c,tinyxmlerror.c,tinyxmlparser.c 放到工程的源文件下,并包含入工程。入下图中把六个文件都包含进来即可。


现在就可以使用这个库来进行解析了。使用方法很简单。

#include "stdafx.h"
#include <iostream>
#include "tinyxml.h"

将这个tinyxml.h头文件包含进来即可。

2.一些基本操作

我要解析的svg格式的内容如下:


我想要获取的是path节点下fill的值,即颜色的值,如#4c4747这样的值。另外解析<g>节点的数量来判断图是否为单色,以及获取<svg>节点下图片的高height和宽width的信息;最后获取M中的所有节点坐标并计算其围成的面积等。下面通过使用tinyxml的一些对象来获取这些内容。下面仅以一段程序来说明功能:

bool ReadXmlFile(string filepath,SvgInfo &svginfo)
{
try
{
svginfo.name=filepath;
//载入svg文件
TiXmlDocument *myDocument =new TiXmlDocument(filepath.c_str());
myDocument->LoadFile();
//获取根节点svg
TiXmlElement *RootElement=myDocument->RootElement();
//cout<<RootElement->Value()<<endl;
//获取文件的大小
TiXmlAttribute *Attr_width=RootElement->FirstAttribute();
//cout<<"Width is "<<Attr_width->Value()<<endl;
TiXmlAttribute *Attr_height=Attr_width->Next();
//cout<<"Height is "<<Attr_height->Value()<<endl;
//处理高和宽成数字
const char *cpwidth=Attr_width->Value();
const char *cpheight=Attr_height->Value();
char *pwidth=const_cast<char *>(cpwidth);
char *pheight=const_cast<char *>(cpheight);
int widthlen=strlen(pwidth)-2;
int heightlen=strlen(pheight)-2;
char *ptempw=new char[widthlen];
char *ptemph=new char[heightlen];
strncpy_s(ptempw,strlen(pwidth),pwidth,widthlen);
strncpy_s(ptemph,strlen(pheight),pheight,heightlen);
float fwidth=atof(ptempw);
float fheight=atof(ptemph);

                  ····················

               //指向节点<g>
TiXmlElement *pelement=RootElement->FirstChildElement();
//cout<<pelement->Value()<<endl;
//指向根节点<path>
pelement=pelement->FirstChildElement();
//cout<<pelement->Value()<<endl;
//指向path的第一个属性fill
TiXmlAttribute *Attr=pelement->FirstAttribute();
//cout<<pelement->FirstAttribute()<<endl;
//cout<<Attr->Value()<<endl;
const char* cpcolor=Attr->Value();
char *pcolor=const_cast<char *>(cpcolor);
pcolor++;
string currentcolor=pcolor;
//指向path的第二个属性opacity
TiXmlAttribute *Attr2=Attr->Next();
//cout<<Attr2->Value()<<endl;
//指向path的第三个属性d,即路径的点
TiXmlAttribute *Nodespos=Attr2->Next();
const char *nodes=Nodespos->Value();

             ··························

            ···························

}

说明:参数中filepath是要处理文件的路径名,例如 D:/test/abc.svg;第二个参数是自己定义的一个结构来存储一些信息的,这里不用管。直接去看如何对其进行操作。

按照载入svg图片注释下的方式进行载入要处理的内容。定义一个TinyXmlDocument;可以视为保存当前文件的一个对象吧。然后就是对其节点的一些操作了。定义一个节点TinyXmlElement,通过获取TinyXmlDocument节点RootElement()来获取第一个节点,即<svg>节点,以后的操作就可以按照节点顺序,节点名称等进行操作了,属性用TinyXmlAttribute来获取其值。通过上面的代码可以很容易学习几个基本操作的使用。另外根据这些方法就可以自己定义一些根据名称获取某个节点值得函数了。TinyXml还不算很完善的库,但是能够提供基本的操作需求了。希望可以帮助大家。谢谢。


1 0
原创粉丝点击