How to get field values and attribute values for a xml document using EXPAT?

Albrecht Schmidt Albrecht.Schmidt at cwi.nl
Sat Aug 14 17:21:08 BST 1999


>>>>> "Srinivasan" == Srinivasan KS <Srinivasan_KS at inf.com> writes:

    -- snip --

    Srinivasan> We are using EXPAT for doing this.Can any body tell
    Srinivasan> which APIs we have to call and the way it should be
    Srinivasan> called to achieve the result.

    -- snip --


You might want to try something like this.  It should be close to what
you want (it's a modified $(EXPATHOME)/sample/elments.c):

#include <stdio.h>
#include "xmlparse.h"

void startElement(void * user_data, const char * name, const char ** atts) {

  int i;
  if (atts)
    for (i = 0; atts [i]; i += 2)
      printf ("%s=\"%s\"\n", atts[i], atts[i+1]); 
}

void endElement(void * user_data, const char * name) {}

int only_whitespace (const XML_Char * s, int len) {
  /* return true if first len characters of s are whitespace;
     used for filtering out uninteresting tokens -- watch your encoding */

  int i;
  for (i = 0; i < len; i++) if (!isspace (s[i])) return 0;
  return 1;
}

void do_character_data (void * user_data, const XML_Char * s, int len) {

  if (!only_whitespace (s, len)) {
    int i;
    for (i = 0; i < len; i++) putchar (s[i]);
    printf ("\n");
  }
}

int main()
{
  char buf[BUFSIZ];
  XML_Parser parser = XML_ParserCreate(NULL);
  int done;
  int depth = 0;
  XML_SetUserData(parser, &depth);
  XML_SetElementHandler(parser, startElement, endElement);
  XML_SetCharacterDataHandler(parser, do_character_data);

  do {
    size_t len = fread(buf, 1, sizeof(buf), stdin);
    done = len < sizeof(buf);
    if (!XML_Parse(parser, buf, len, done)) {
      fprintf(stderr,
	      "%s at line %d\n",
	      XML_ErrorString(XML_GetErrorCode(parser)),
	      XML_GetCurrentLineNumber(parser));
      return 1;
    }
  } while (!done);
  XML_ParserFree(parser);
  return 0;
}

compile with (under UNIX):

gcc -I../xmlparse -o e ../xmlparse/*.o ../xmltok/*.o e.c

execute with:

e < some_xml_file.xml

Regards,

Al.

xml-dev: A list for W3C XML Developers. To post, mailto:xml-dev at ic.ac.uk
Archived as: http://www.lists.ic.ac.uk/hypermail/xml-dev/ and on CD-ROM/ISBN 981-02-3594-1
To (un)subscribe, mailto:majordomo at ic.ac.uk the following message;
(un)subscribe xml-dev
To subscribe to the digests, mailto:majordomo at ic.ac.uk the following message;
subscribe xml-dev-digest
List coordinator, Henry Rzepa (mailto:rzepa at ic.ac.uk)





More information about the Xml-dev mailing list