Saturday, July 17, 2010

libxml2: XML parsing using C/C++

http://www.xmlsoft.org/

require some modification:
xmlversion.h

/**
* LIBXML_ICONV_ENABLED:
*
* Whether iconv support is available
*/
#if 0 // instead of 1
#define LIBXML_ICONV_ENABLED
#endif


iconv.dll required. got it at: http://www.gnupg.org/download/iconv.en.html


xmlTextReaderPtr reader;
char xml[200] = "<root><child1><child2 attr=\"123\" attr2=\"test\">hello world</child2></child1></root>";
printf("%s\n", xml);
cout << "Read XML from memory...\n";
reader = xmlReaderForMemory(xml, strlen(xml), "", NULL, 0);
if (reader != NULL) {
// loop to read nodes
int ret;
const xmlChar *name, *value;
ret = xmlTextReaderRead(reader);
while(ret == 1)
{
name = xmlTextReaderConstName(reader);
value = xmlTextReaderConstValue(reader);
printf("%s=%s\n", name, value);

// attributes
ret = xmlTextReaderHasAttributes(reader);
if(ret == 1)
{
// has attributes
attrName = xmlCharStrdup("attr");
attrValue = xmlTextReaderGetAttribute(reader, attrName);
int attr = atoi((const char *) attrValue);

printf("attr=%d\n", attr);

}

ret = xmlTextReaderRead(reader);
}

cout << "Freeing XML reader...\n";
xmlFreeTextReader(reader);

}

No comments: