使用Libxml2解析xml

       今天介绍的方法为使用Dom树解析,将给出两个  实例,说明如何使用Libxml2遍历xml文档和使Xpath获取特定结点的内容值:(程序使用的xml文档为<?xml version="1.0" encoding="UTF-8"?>
     <root>               <node1>content of node 1</node1>
                              <node3 attribute="yes">node has attributes</node3>
                              <node4>other way to create content</node>                       </root>)


             遍历程序代码

           #include <iostream>
           #include <libxml/parser.h>
           #include <libxml/tree.h>
            using namespace std;

            int main(int argc,char** argv)
            {
                     xmlDocPtr doc=NULL;
                     xmlNodePtr  cur=NULL;
                     char* name=NULL;
                     char* value=NULL;
 
                    xmlKeepBlanksDefault (0); 

                    if(argc<2)
                    {
                              cout<<"argc must be 2 or above."<<endl;
                              return -1;
                     }
     
                    doc=xmlParseFile(argv[1]);//创建Dom树
                    if(doc==NULL)
                   {
                             cout<<"Loading xml file failed."<<endl;
                             exit(1); 
                     }
 
                   cur=xmlDocGetRootElement(doc);//获取根节点
                   if(cur==NULL)
                   {
                             cout<<"empty file"<<endl;
                             xmlFreeDoc(doc); 
                             exit(2); 
                    }

                   //walk the tree 
                   cur=cur->xmlChildrenNode;//get sub node
                   while(cur !=NULL)
                  {
                               name=(char*)(cur->name); 
                               value=(char*)xmlNodeGetContent(cur);
                              cout<<"name is: "<<name<<", value is: "<<value<<endl;
                               xmlFree(value); 
                              cur=cur->next;  
                   }
 
                   xmlFreeDoc(doc);//释放xml解析库所用资源
                   xmlCleanupParser();
                   return 0;
          }

                   说明:

                     1.  当使用dom树来解析xml文档时,由于默认的方式是把节点间的空白当作第一个子

                         节 点,所以为了能和常说的第一个子节点相符,需调用xmlKeepBlanksDefault (0)函数

                         来忽略这种空白。

                     2.   对于使用xmlChar* xmlNodeGetContent(xmlNodePtr cur)函数获取节点内容后,必须调

                        用xmlFree()来对所分配的内存进行释放。

                 使用Xpath获取特定结点的内容(使用的xml文档见上面):

    #include <iostream>
    #include <string>
    using namespace std;

    #include <libxml/tree.h>
    #include <libxml/parser.h>
    #include <libxml/xpath.h>
    #include <libxml/xpathInternals.h>

int main(int argc,char** argv)
{
    xmlDocPtr doc;
    xmlXPathContextPtr xpathCtx;
    xmlXPathObjectPtr xpathObj;
    xmlNodeSetPtr  nodeset;
   string xpathExpr;
    char*  val=NULL;
    int size,i;
   
    if(argc<2)
    {
     cout<<"argc must be 2 or above."<<endl;
     return -1;
    }
   
    /* Load XML document */
    doc = xmlParseFile(argv[1]);
    if (doc == NULL)
    {
        cout<<"Error: unable to parse file: "<<argv[1]<<endl;   
        return -1;
    }

    /* Create xpath evaluation context */
    xpathCtx = xmlXPathNewContext(doc);
    if(xpathCtx == NULL)
    {
        cout<<"Error: unable to create new XPath context"<<endl;
        xmlXPathFreeContext(xpathCtx);
        xmlFreeDoc(doc);
        return -2;
    }

    xpathExpr="/root/node3";
    /* Evaluate xpath expression */
    xpathObj = xmlXPathEvalExpression((const xmlChar*)(xpathExpr.c_str()), xpathCtx);
    if(xpathObj == NULL)
    {
        cout<<"Error: unable to evaluate xpath expression"<<xpathExpr<<endl;
        xmlXPathFreeContext(xpathCtx);
        xmlFreeDoc(doc);
        return -3;
    }
   
    /* get values of the selected nodes */
    nodeset=xpathObj->nodesetval;
    if(xmlXPathNodeSetIsEmpty(nodeset))
    {
        cout<<"No such nodes."<<endl;
        xmlXPathFreeObject(xpathObj);
        xmlXPathFreeContext(xpathCtx);
        xmlFreeDoc(doc);
       return -4;
     }
   
    //get the value   
    size = (nodeset) ? nodeset->nodeNr : 0;
    for(i = 0; i <size; i++)
    {
        val=(char*)xmlNodeListGetString(doc, nodeset->nodeTab[i]->xmlChildrenNode, 1);       
        cout<<"the results are: "<<val<<endl;
        xmlFree(val);
    } 
   
    //Cleanup of XPath data
    xmlXPathFreeObject(xpathObj);
    xmlXPathFreeContext(xpathCtx);    
    /* free the document */
    xmlFreeDoc(doc);
    xmlCleanupParser();
    return 0;
}

  

 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值