libxml2实例

转自:http://blog.sina.com.cn/s/blog_5ea0192f0100w73j.html

1、关于XML:

在开始研究 Libxml2 库之前,先了解一下XML的相关基础。XML是一种基于文本的格式,它可用来创建能够通过各种语言和平台访问的结构化数据。它包括一系列类似 HTML的标记,并以树型结构来对这些标记进行排列。

例如,可参见清单 1 中介绍的简单文档。为了更清楚地显示 XML 的一般概念,下面是一个简化的XML文件。

清单 1. 一个简单的 XML 文件

            <?xml version="1.0"encoding="UTF-8"?>

            <files>

                 <owner>root</owner>

                 <action>delete</action>

                 <ageunits="days">10</age>

            </files>

清单 1 中的第一行是 XML 声明,它告诉负责处理 XML 的应用程序,即解析器,将要处理的 XML的版本。大部分的文件使用版本 1.0 编写,但也有少量的版本 1.1 的文件。它还定义了所使用的编码。大部分文件使用UTF-8,但是,XML 设计用来集成各种语言中的数据,包括那些不使用英语字母的语言。

接下来出现的是元素。一个元素以开始标记 开始(如<files>),并以结束标记 结束(如</files>),其中使用斜线 (/) 来区别于开始标记。元素是Node 的一种类型。XML 文档对象模型 (DOM) 定义了几种不同的 Nodes 类型,包括:

Elements(如 files 或者 age)

Attributes(如 units)

Text(如 root 或者 10)

元素可以具有子节点。例如,age 元素有一个子元素,即文本节点 10。

XML 解析器可以利用这种父子结构来遍历文档,甚至修改文档的结构或内容。LibXML2是这样的解析器中的其中一种,并且文中的示例应用程序正是使用这种结构来实现该目的。对于各种不同的环境,有许多不同的解析器和库。LibXML2是用于 UNIX 环境的解析器和库中最好的一种,并且经过扩展,它提供了对几种脚本语言的支持,如 Perl 和 Python。

2.      Libxml2中的数据类型和函数
一个函数库中可能有几百种数据类型以及几千个函数,但是记住大师的话,90%的功能都是由30%的内容提供的。对于libxml2,我认为搞懂以下的数据类型和函数就足够了。

2.1   内部字符类型xmlChar
xmlChar是Libxml2中的字符类型,库中所有字符、字符串都是基于这个数据类型。事实上它的定义是:xmlstring.h

typedef unsigned char xmlChar;

使用unsignedchar作为内部字符格式是考虑到它能很好适应UTF-8编码,而UTF-8编码正是libxml2的内部编码,其它格式的编码要转换为这个编码才能在libxml2中使用。

还经常可以看到使用xmlChar*作为字符串类型,很多函数会返回一个动态分配内存的xmlChar*变量,使用这样的函数时记得要手动删除内存。

2.2   xmlChar相关函数
如同标准c中的char类型一样,xmlChar也有动态内存分配、字符串操作等相关函数。例如xmlMalloc是动态分配内存的函数;xmlFree是配套的释放内存函数;xmlStrcmp是字符串比较函数等等。

基本上xmlChar字符串相关函数都在xmlstring.h中定义;而动态内存分配函数在xmlmemory.h中定义。

2.3   xmlChar*与其它类型之间的转换
另外要注意,因为总是要在xmlChar*和char*之间进行类型转换,所以定义了一个宏BAD_CAST,其定义如下:xmlstring.h

#define BAD_CAST (xmlChar *)

原则上来说,unsigned char和char之间进行强制类型转换是没有问题的。

2.4  文档类型xmlDoc、指针xmlDocPtr
xmlDoc是一个struct,保存了一个xml的相关信息,例如文件名、文档类型、子节点等等;xmlDocPtr等于xmlDoc*,它搞成这个样子总让人以为是智能指针,其实不是,要手动删除的。

xmlNewDoc函数创建一个新的文档指针。

xmlParseFile函数以默认方式读入一个UTF-8格式的文档,并返回文档指针。

xmlReadFile函数读入一个带有某种编码的xml文档,并返回文档指针;细节见libxml2参考手册。

xmlFreeDoc释放文档指针。特别注意,当你调用xmlFreeDoc时,该文档所有包含的节点内存都被释放,所以一般来说不需要手动调用xmlFreeNode或者xmlFreeNodeList来释放动态分配的节点内存,除非你把该节点从文档中移除了。一般来说,一个文档中所有节点都应该动态分配,然后加入文档,最后调用xmlFreeDoc一次释放所有节点申请的动态内存,这也是为什么我们很少看见xmlNodeFree的原因。

xmlSaveFile将文档以默认方式存入一个文件。

xmlSaveFormatFileEnc可将文档以某种编码/格式存入一个文件中。

2.5  节点类型xmlNode、指针xmlNodePtr
节点应该是xml中最重要的元素了,xmlNode代表了xml文档中的一个节点,实现为一个struct,内容很丰富:tree.h
typedef struct _xmlNode xmlNode;
typedef xmlNode *xmlNodePtr;
struct _xmlNode {
    void          *_private;
    xmlElementType  type;  
    constxmlChar  *name;     
    struct_xmlNode *children;
    struct_xmlNode *last;  
    struct_xmlNode *parent;
    struct_xmlNode *next;  
    struct_xmlNode *prev;  
    struct_xmlDoc *doc;
   

    xmlNs          *ns;       
    xmlChar        *content;  
    struct_xmlAttr *properties;
    xmlNs          *nsDef;    
    void           *psvi;
    unsignedshort  line;  
    unsignedshort   extra;
};

可以看到,节点之间是以链表和树两种方式同时组织起来的,next和prev指针可以组成链表,而parent和children可以组织为树。同时还有以下重要元素:

        节点中的文字内容:content;
        节点所属文档:doc;
        节点名字:name;
        节点的namespace:ns;
        节点属性列表:properties;

Xml文档的操作其根本原理就是在节点之间移动、查询节点的各项信息,并进行增加、删除、修改的操作。

xmlDocSetRootElement函数可以将一个节点设置为某个文档的根节点,这是将文档与节点连接起来的重要手段,当有了根结点以后,所有子节点就可以依次连接上根节点,从而组织成为一个xml树。

2.6  节点集合类型xmlNodeSet、指针xmlNodeSetPtr
节点集合代表一个由节点组成的变量,节点集合只作为Xpath的查询结果而出现(XPATH的介绍见后面),因此被定义在xpath.h中,其定义如下:


typedef struct _xmlNodeSet xmlNodeSet;
typedef xmlNodeSet *xmlNodeSetPtr;
struct _xmlNodeSet {

    intnodeNr;         

    intnodeMax;     

    xmlNodePtr *nodeTab;

};

可以看出,节点集合有三个成员,分别是节点集合的节点数、最大可容纳的节点数,以及节点数组头指针。对节点集合中各个节点的访问方式很简单,如下:
xmlNodeSetPtr nodeset = XPATH查询结果;
for (int i = 0; i < nodeset->nodeNr;i++)
{

      nodeset->nodeTab[i];
}
注意,libxml2是一个c函数库,因此其函数和数据类型都使用c语言的方式来处理。如果是c++,我想我宁愿用STL中的vector来表示一个节点集合更好,而且没有内存泄漏或者溢出的担忧。

3.1   创建xml文档
有了上面的基础,创建一个xml文档显得非常简单,其流程如下:
        用xmlNewDoc函数创建一个文档指针doc;
        用xmlNewNode函数创建一个节点指针root_node;
        用xmlDocSetRootElement将root_node设置为doc的根结点;
        给root_node添加一系列的子节点,并设置子节点的内容和属性;
        用xmlSaveFile将xml文档存入文件;
        用xmlFreeDoc函数关闭文档指针,并清除本文档中所有节点动态申请的内存。
注意,有多种方式可以添加子节点:第一是用xmlNewTextChild直接添加一个文本子节点;第二是先创建新节点,然后用xmlAddChild将新节点加入上层节点。

#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <iostream.h>

int main()
{
   //定义文档和节点指针
    xmlDocPtrdoc = xmlNewDoc(BAD_CAST"1.0");

   xmlNodePtr root_node = xmlNewNode(NULL,BAD_CAST"root");

   //设置根节点
   xmlDocSetRootElement(doc,root_node);

   //在根节点中直接创建节点
   xmlNewTextChild(root_node, NULL, BAD_CAST "newNode1", BAD_CAST"newNode1 content");

   xmlNewTextChild(root_node, NULL, BAD_CAST "newNode2", BAD_CAST"newNode2 content");

   xmlNewTextChild(root_node, NULL, BAD_CAST "newNode3", BAD_CAST"newNode3 content");

   //创建一个节点,设置其内容和属性,然后加入根结点
    xmlNodePtrnode = xmlNewNode(NULL,BAD_CAST"node2");

   xmlNodePtr content = xmlNewText(BAD_CAST"NODE CONTENT");

   xmlAddChild(root_node,node);

   xmlAddChild(node,content);

   xmlNewProp(node,BAD_CAST"attribute",BAD_CAST "yes");

   //创建一个儿子和孙子节点
    node =xmlNewNode(NULL, BAD_CAST "son");

   xmlAddChild(root_node,node);

   xmlNodePtr grandson = xmlNewNode(NULL, BAD_CAST "grandson");

   xmlAddChild(node,grandson);

   xmlAddChild(grandson, xmlNewText(BAD_CAST "This is a grandsonnode"));

   //存储xml文档
    int nRel =xmlSaveFile("CreatedXml.xml",doc);
    if (nRel !=-1)
    {
      cout<<"一个xml文档被创建,写入"<<nRel<<"个字节"<<endl;
    }

   //释放文档内节点动态申请的内存
   xmlFreeDoc(doc);

    return1;
}

3.2   解析xml文档

解析一个xml文档,从中取出想要的信息,例如节点中包含的文字,或者某个节点的属性,其流程如下:
        用xmlReadFile函数读出一个文档指针doc;
        用xmlDocGetRootElement函数得到根节点curNode;
        curNode->xmlChildrenNode就是根节点的子节点集合;
        轮询子节点集合,找到所需的节点,用xmlNodeGetContent取出其内容;
        用xmlHasProp查找含有某个属性的节点;
        取出该节点的属性集合,用xmlGetProp取出其属性值;
       用xmlFreeDoc函数关闭文档指针,并清除本文档中所有节点动态申请的内存。
注意:节点列表的指针依然是xmlNodePtr,属性列表的指针也是xmlAttrPtr,并没有xmlNodeList或者xmlAttrList这样的类型。看作列表的时候使用它们的next和prev链表指针来进行轮询。只有在Xpath中有xmlNodeSet这种类型,其使用方法前面已经介绍了。

#include <libxml/parser.h>
#include <iostream.h>

int main(int argc, char* argv[])
{
    xmlDocPtrdoc;          //定义解析文档指针
    xmlNodePtrcurNode;     //定义结点指针(你需要它为了在各个结点间移动)
    xmlChar*szKey;         //临时字符串变量
    char*szDocName;

    if (argc<= 1)
    {
      printf("Usage: %s docname"n", argv[0]);

      return(0);
    }

    szDocName= argv[1];
    doc =xmlReadFile(szDocName,"GB2312",XML_PARSE_RECOVER); //解析文件
   //检查解析文档是否成功,如果不成功,libxml将指一个注册的错误并停止。
   //一个常见错误是不适当的编码。XML标准文档除了用UTF-8或UTF-16外还可用其它编码保存。
   //如果文档是这样,libxml将自动地为你转换到UTF-8。更多关于XML编码信息包含在XML标准中.

    if (NULL== doc)
   
      fprintf(stderr,"Document not parsed successfully. "n");

      return -1;
    }

    curNode =xmlDocGetRootElement(doc); //确定文档根元素

   
    if (NULL ==curNode)
    {
      fprintf(stderr,"empty document"n");
      xmlFreeDoc(doc);
      return -1;
    }

   
    if(xmlStrcmp(curNode->name, BAD_CAST "root"))
    {
      fprintf(stderr,"document of the wrong type, root node !=root");

      xmlFreeDoc(doc);

      return -1;
    }

    curNode =curNode->xmlChildrenNode;

   xmlNodePtr propNodePtr = curNode;

   while(curNode != NULL)
    {
      //取出节点中的内容
      if ((!xmlStrcmp(curNode->name, (const xmlChar*)"newNode1")))
      {
          szKey = xmlNodeGetContent(curNode);

          printf("newNode1: %s"n", szKey);

          xmlFree(szKey);
      }

      //查找带有属性attribute的节点
      if (xmlHasProp(curNode,BAD_CAST "attribute"))
      {
          propNodePtr = curNode;
      }

      curNode = curNode->next;
    }

   //查找属性
    xmlAttrPtrattrPtr = propNodePtr->properties;

    while(attrPtr != NULL)
    {
      if (!xmlStrcmp(attrPtr->name, BAD_CAST"attribute"))
      {
          xmlChar* szAttr = xmlGetProp(propNodePtr,BAD_CAST "attribute");

          cout<<"get attribute ="<<szAttr<<endl;

          xmlFree(szAttr);
      }

      attrPtr = attrPtr->next;
    }

   xmlFreeDoc(doc);

    return0;
}

3.3   修改xml文档
有了上面的基础,修改xml文档的内容就很简单了。首先打开一个已经存在的xml文档,顺着根结点找到需要添加、删除、修改的地方,调用相应的xml函数对节点进行增、删、改操作。

示例3:

得到一个节点的内容:
   xmlChar *value =xmlNodeGetContent(node);
  返回值value应该使用xmlFree(value)释放内存

得到一个节点的某属性值:
   xmlChar *value =xmlGetProp(node, (const xmlChar *)"prop1");
   返回值需要xmlFree(value)释放内存

设置一个节点的内容:
   xmlNodeSetContent(node, (constxmlChar *)"test");

设置一个节点的某属性值:
   xmlSetProp(node, (constxmlChar *)"prop1", (const xmlChar *)"v1");

添加一个节点元素:
   xmlNewTextChild(node, NULL,(const xmlChar *)"keyword", (const xmlChar *)"test Element");

添加一个节点属性:
   xmlNewProp(node, (constxmlChar *)"prop1", (const xmlChar *)"test Prop");


需要注意的是,并没有xmlDelNode或者xmlRemoveNode函数,我们删除节点使用的是以下一段代码:

      if (!xmlStrcmp(curNode->name, BAD_CAST"newNode1"))
      {
          xmlNodePtr tempNode;

          tempNode = curNode->next;

          xmlUnlinkNode(curNode);

          xmlFreeNode(curNode);

          curNode = tempNode;

          continue;
      }

即将当前节点从文档中断链(unlink),这样本文档就不会再包含这个子节点。这样做需要使用一个临时变量来存储断链节点的后续节点,并记得要手动删除断链节点的内存。


3.4   使用XPATH查找xml文档
要在一个复杂的xml文档中查找所需的信息,XPATH简直是必不可少的工具。XPATH语法简单易学,并且有一个很好的官方教程,见http://www.zvon.org/xxl/XPathTutorial/Output_chi/introduction.html。这个站点的XML各种教程齐全,并且有包括中文在内的各国语言版本,真是让我喜欢到非常!

使用XPATH之前,必须首先熟悉几个数据类型和函数,它们是使用XPATH的前提。在libxml2中使用Xpath是非常简单的,其流程如下:
        定义一个XPATH上下文指针xmlXPathContextPtrcontext,并且使用xmlXPathNewContext函数来初始化这个指针;
        定义一个XPATH对象指针xmlXPathObjectPtrresult,并且使用xmlXPathEvalExpression函数来计算Xpath表达式,得到查询结果,将结果存入对象指针中;
        使用result->nodesetval得到节点集合指针,其中包含了所有符合Xpath查询结果的节点;
        使用xmlXPathFreeContext释放上下文指针;
        使用xmlXPathFreeObject释放Xpath对象指针;

具体的使用方法可以看XpathForXmlFile.cpp的这一段代码,其功能是查找符合某个Xpath语句的对象指针:
xmlXPathObjectPtr getNodeSet(xmlDocPtr doc, const xmlChar*szXpath)
{
   xmlXPathContextPtrcontext;   //XPATH上下文指针

   xmlXPathObjectPtrresult;      //XPATH对象指针,用来存储查询结果

    context =xmlXPathNewContext(doc);    //创建一个XPath上下文指针

    if(context == NULL)
   
      printf("context is NULL"n");

      return NULL;
    }

    result =xmlXPathEvalexpression_r(szXpath, context);//查询XPath表达式,得到一个查询结果
   xmlXPathFreeContext(context);            //释放上下文指针

    if(result == NULL)
    {
      printf("xmlXPathEvalExpression return NULL"n");

      return NULL;
    }

    if(xmlXPathNodeSetIsEmpty(result->nodesetval))  //检查查询结果是否为空
    {
      xmlXPathFreeObject(result);

      printf("nodeset is empty"n");

      return NULL;
    }

    returnresult;
}

4.用ICONV解决XML中的中文问题
Libxml2中默认的内码是UTF-8,所有使用libxml2进行处理的xml文件,必须首先显式或者默认的转换为UTF-8编码才能被处理。

下面的示例程序提供几个函数来实现对数据编码格式的转换,其中有的要用到Libiconv,因此为了确保他们能正常工作,先检查以下系统中是否已经安装libiconv库。

示例6:

xmlChar *ConvertInput(const char *in, const char *encoding){
   unsigned char *out;
   int ret;
   int size;
   int out_size;
   int temp;

   xmlCharEncodingHandlerPtrhandler;

   if (in == 0)
    return0;
   
   handler =xmlFindCharEncodingHandler(encoding);

   if (!handler) {
   printf("ConvertInput: no encoding handler found for '%s'\n",encoding ? encoding : "");
    return0;
   }

   size = (int) strlen(in) +1;

   out_size = size * 2 -1;

   out = (unsigned char *)xmlMalloc((size_t) out_size); 

   if (out != 0) {
    temp = size- 1;
    ret =handler->input(out, &out_size,(const unsigned char *) in, &temp);

    if ((ret< 0) || (temp - size + 1)) {
    if (ret < 0) {
     printf("ConvertInput: conversion wasn't successful.\n");
    } else {
     printf("ConvertInput:conversion wasn't successful. converted: %ioctets.\n", temp);
    }

     xmlFree(out);
    out = 0;
    } else{
    out = (unsigned char *) xmlRealloc(out, out_size + 1);
    out[out_size] = 0;
    }
   } else {
   printf("ConvertInput: no mem\n");
   }

   return out;
}


示例7:

char * Convert( char *encFrom, char *encTo, const char * in){
   static char bufin[1024],bufout[1024], *sin, *sout;
   int mode, lenin, lenout, ret,nline;
  
   iconv_t c_pt;

   if ((c_pt =iconv_open(encTo, encFrom)) == (iconv_t)-1) {
   printf("iconv_open false: %s ==> %s\n", encFrom,encTo);
    returnNULL;
   }

   iconv(c_pt, NULL, NULL,NULL, NULL);

   lenin = strlen(in) +1;
   lenout = 1024;
  sin    = (char*)in;
  sout   = bufout;

   ret = iconv(c_pt,&sin, (size_t *)&lenin,&sout, (size_t*)&lenout);        

   if (ret == -1) {
    returnNULL;
   }
  
   iconv_close(c_pt);
  
   return bufout;
}

 

5.libxml2 xmlNodeType
http://www.gnu.org/software/dotgnu/pnetlib-doc/System/Xml/XmlNodeType.html

5.1 An Attribute node can have the following child node types:Text and EntityReference . The Attribute node does not appear asthe child node of any other node type. It is not considered a childnode of an Element
id="123"

5.2 CDATA sections are used to escape blocks of text that wouldotherwise be recognized as markup. A CDATA node cannot have anychild nodes. It can appear as the child of the DocumentFragment ,EntityReference , and Element nodes.
<![CDATA[escaped text]]>

5.3 A Comment node cannot have any child nodes. It can appear asthe child of the Document , DocumentFragment , Element , andEntityReference nodes.
<!-- comment -->

5.4  document object that, as the root of thedocument tree, provides access to the entire XML document.
A Document node can have the following child node types:XmlDeclaration , Element (maximum of one), ProcessingInstruction ,Comment , and DocumentType . It cannot appear as the child of anynode types.

5.5 A document fragment.
The DocumentFragment node associates a node or sub-tree with adocument without actually being contained within the document. ADocumentFragment node can have the following child node types:Element , ProcessingInstruction , Comment , Text , CDATA , andEntityReference . It cannot appear as the child of any nodetypes.

5.6 The document type declaration, indicated by the followingtag.
A DocumentType node can have the following child node types:Notation and Entity . It can appear as the child of the Documentnode.
<!DOCTYPE ...>

5.7 An Element node can have the following child node types:Element , Text , Comment , ProcessingInstruction , CDATA , andEntityReference . It can be the child of the Document ,DocumentFragment , EntityReference , and Element nodes.
<name>

5.8 An end element. Returned when XmlReader gets to the end ofan element.
</name>

5.9 Returned when XmlReader gets to the end of the entityreplacement as a result of a call toSystem.Xml.XmlReader.ResolveEntity .

5.10 An entity declaration.
An Entity node can have child nodes that represent the expandedentity (for example, Text and EntityReference nodes). It can appearas the child of the DocumentType node.
<!ENTITY ...>

5.11 The text content of a node.
A Text node cannot have any child nodes. It can appear as the childnode of the Attribute , DocumentFragment , Element , andEntityReference nodes.


5.12 The XML declaration.
The XmlDeclaration node must be the first node in the document. Itcannot have children. It is a child of the Document node. It canhave attributes that provide version and encodinginformation.
<?xml version="1.0"?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值