Thursday, May 21, 2009

Simple Example to extract data from xml file using expat............

takes an xml file and extract attributes into a file .rtf


#include "stdio.h"
#include "expat.h"
#include"string.h"
#define BUFFSIZE 8000



FILE *rtfFile;


static void startElement(void *cargo, const char *el,const char **attr)
{
}
static void endElement(void *cargo, const char *el)
{
}
static void characters(void *cargo, const char *ch, int len)
{
int i;
for (i=0; i putc(ch[i],rtfFile);
}

int main(int argc, char *argv[])
{
if(argc!=3)
{
printf("\nUsage : \n");
exit(0);
}
char Buff[BUFFSIZE];
FILE *fp;

fp = fopen(argv[1],"r");
rtfFile = fopen(strcat(argv[2],".rtf"),"w");

XML_Parser parser = XML_ParserCreate(NULL);
XML_SetElementHandler(parser, startElement, endElement);
XML_SetCharacterDataHandler(parser, characters);

for (;;)
{
int len = fread(Buff, 1, BUFFSIZE, fp);
int done = feof(fp);
if (! XML_Parse(parser, Buff, len, done))
exit(-1);
if (done) break;
}
fclose(fp);
printf("\n");
fclose(rtfFile);
return 0;
}


for Example we can use following content of a

< ?xml version="1.0"?>
< story>
< storyinfo>
< author>Ranjeet Kumar</author>
< datewritten>October 15,1985 </datewritten>
< keyword>Don</keyword>
< /storyinfo>
< body >
< headline > It's not gonna to help you < /headline >
< para > Don't be fool < /para >
< /body >
< /story >

No comments:

Post a Comment

Search Ranjeet's Blog