您的位置:首页 > 其它

使用libxml2对xml进行SAX读取

2012-11-23 12:23 281 查看
//下面的程序是从这里的例子修改过来的

//查找并打印出<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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: