954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to parse XML file in C?

i have a XML file containing data, i want to parse it in c. can you help me out in parsing.

harris21
Newbie Poster
9 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
 

I use the expat library in my application.

http://expat.sourceforge.net

Its robust, easy to use, open source, and recommended by the XML organization. I highly recommend it.

It uses callback functions, so what you do is open your file with fopen, then loop through each character and feed it to XML_Parse() like this...

int Parse(FILE *in_Stream) {

  XML_Parser p = XML_ParserCreate(NULL);
  if (! p) {
    fprintf(stderr, "Couldn't allocate memory for parser\n");
    return -1;
  }

  XML_UseParserAsHandlerArg(p);
  XML_SetElementHandler(p, start_hndl, end_hndl);
  XML_SetCharacterDataHandler(p, char_hndl);
  XML_SetProcessingInstructionHandler(p, proc_hndl);

  char buff;
  int  done = 0;
  for (fread(&buff, sizeof(char), 1, in_Stream); !feof(in_Stream); fread(&buff, sizeof(char), 1, in_Stream))
     if (! XML_Parse(p, &buff, sizeof(char), done)) {
        fprintf(stderr, "Parse error at line %d:\n%s\n",
          XML_GetCurrentLineNumber(p),
          XML_ErrorString(XML_GetErrorCode(p)));
        return -1;
     }
  return 0;

}


Then you use its callback functions to deal with the individual elements. TheXML_Parse() function will call those event functions as soon as it detects that a new complete element has been received.

For instance, start_hndl() is called by the XML engine to tell you when something like "" or the tag was formatted like this "", it will call end_hndl() passing the same name "Image", so you know which tag it belongs to.

The sample program that comes with the library should be very easy to understand.

N1GHTS
Posting Whiz in Training
275 posts since Sep 2010
Reputation Points: 115
Solved Threads: 18
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: