使用libxml2對xml進行SAX讀取

//下面的程序是從這裏的例子修改過來的

//查找並打印出<w:sectPr>元素,屬性值,和它的子元素值

//屬性值必須在雙引號裏面,否則libxml通過SAX解析不了

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string>
#include <iostream>

#include "libxml/SAX2.h"
#include "libxml/xmlstring.h"

int g_element_count = 0;
static void OnStartElementNs(
    void *ctx,
    const xmlChar *localname,
    const xmlChar *prefix,
    const xmlChar *URI,
    int nb_namespaces,
    const xmlChar **namespaces,
    int nb_attributes,
    int nb_defaulted,
    const xmlChar **attributes)
{
    if (!xmlStrcmp(localname, BAD_CAST"sectPr"))
    {
        ++g_element_count;
        std::cout<<"<<<<<<<<<<<<<<<<<<<<<<"<<std::endl<<std::endl;
    }

    if (g_element_count)
    {
        std::cout<<"element : "<< prefix<<":"<<localname << std::endl;
        for (int i=0; i<nb_attributes; ++i)
        {
            std::string str = (char *)attributes[5*i+3];
            xmlChar *attr_value = xmlCharStrdup(str.substr(0, str.find("\"")).c_str());
            std::cout<<"<<<< "<<attributes[5*i+1]<<":"<<attributes[5*i]<< "=" << attr_value <<std::endl;
            xmlFree(attr_value);
        }
    }
}


static void OnEndElementNs(
    void* ctx,
    const xmlChar* localname,
    const xmlChar* prefix,
    const xmlChar* URI )
{
    if (!xmlStrcmp(localname, BAD_CAST"sectPr"))
    {
        --g_element_count;
    }
}


static void OnCharacters(void *ctx, const xmlChar *ch, int len)
{
    if (g_element_count)
    {
        std::string str = (char *)ch;
        std::string value = str.substr(0, str.find('<'));
        std::cout<<value<<std::endl;
    }
}


int FindElement(FILE *f)
{
    char chars[1024];
    int res = fread(chars, 1, 4, f);
    if (res <= 0)
    {
        return 1;
    }

    xmlInitParser();

    xmlSAXHandler SAXHander;
    memset(&SAXHander, 0, sizeof(xmlSAXHandler));
    SAXHander.initialized = XML_SAX2_MAGIC;
    SAXHander.startElementNs = OnStartElementNs;
    SAXHander.endElementNs = OnEndElementNs;
    SAXHander.characters = OnCharacters;

    xmlParserCtxtPtr ctxt = xmlCreatePushParserCtxt(
        &SAXHander, NULL, chars, res, NULL
    );

    while ((res = fread(chars, 1, sizeof(chars)-1, f)) > 0)
    {
        if(xmlParseChunk(ctxt, chars, res, 0))
        {
            xmlParserError(ctxt, "xmlParseChunk");
            return 1;
        }
    }
    xmlParseChunk(ctxt, chars, 0, 1);

    xmlFreeParserCtxt(ctxt);
    xmlCleanupParser();
    return 0;
}


int main(int argc, char *argv[])
{
    FILE *fd = fopen(argv[1], "rb");
    FindElement(fd);
    fclose(fd);
    return 0;
}


 



 

發佈了39 篇原創文章 · 獲贊 5 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章