您的位置:首页 > 运维架构 > Linux

Linux 下C/C++解析XML文件

2015-11-27 16:11 477 查看
在工程项目中我们的项目需要根据不同的环境配置不同的程序参数,而常用的两种文件分别是ini文件和XML文件,接下来我来分析下在Linux下解析XML文件过程。

我们首先使用linux自带的libxml2来解析XML文件。

在libxml2中比较重要的数据结构是xmlNodePtr,它在libxml/tree.h中定义为
/**
* xmlNode:
*
* A node in an XML tree.
*/
typedef struct _xmlNode xmlNode;
typedef xmlNode *xmlNodePtr;
struct _xmlNode {
void           *_private;	/* application data */
xmlElementType   type;	/* type number, must be second ! */
const xmlChar   *name;      /* the name of the node, or the entity */
struct _xmlNode *children;	/* parent->childs link */
struct _xmlNode *last;	/* last child link */
struct _xmlNode *parent;	/* child->parent link */
struct _xmlNode *next;	/* next sibling link  */
struct _xmlNode *prev;	/* previous sibling link  */
struct _xmlDoc  *doc;	/* the containing document */

/* End of common part */
xmlNs           *ns;        /* pointer to the associated namespace */
xmlChar         *content;   /* the content */
struct _xmlAttr *properties;/* properties list */
xmlNs           *nsDef;     /* namespace definitions on this node */
void            *psvi;	/* for type/PSVI informations */
unsigned short   line;	/* line number */
unsigned short   extra;	/* extra data for XPath/XSLT */
};


解析代码如下:

使用的XML文件如下
<?xml version="1.0" encoding="UTF-8"?>
<root>
<monitor>
<name>ftp</name>   <!--监控的程序名称-->
<path>/usr/bin/</path>   <!--程序绝对路径-->
<interval>30</interval>  <!--间隔多久监控一次-->
<restartwait>30</restartwait>  <!--程序被重启后,等待多久再进行监控-->
<ip>127.0.0.1</ip>   <!--程序IP-->
<port>9878</port>    <!--程序端口-->
<request>1;monitor</request>    <!--发送给程序的报文-->
<response>The ftp is working ok.</response>   <!--程序给监控的反馈报文-->
<log>
<folderpath>log/</folderpath>  <!--程序日志保存目录-->
<savedays>2</savedays>     <!--程序日志保存时间-->
</log>
</monitor>
</root>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: