I had a request recently for a simple example of how to use the XmlTextReader interface to Libxml2. This interface simply traverses a document node by node, so it's perfect if you just want to read a file in incrementally, but is not suitable should you need to run XSLT queries on the whole document.
Here is the code:
#include <stdio.h>
#include <libxml/xmlreader.h>
int main(){
xmlTextReaderPtr reader;
/* initialize libxml2 */
LIBXML_TEST_VERSION
reader = xmlNewTextReaderFilename("my_file.xml");
while ( xmlTextReaderRead(reader) ) {
fprintf(stdout,"ConstName=%s\n",xmlTextReaderConstName(reader));
fprintf(stdout,"LocalName=%s\n",xmlTextReaderLocalName(reader));
fprintf(stdout,"Name=%s\n",xmlTextReaderName(reader));
fprintf(stdout,"NodeType=%d\n",xmlTextReaderNodeType(reader));
fprintf(stdout,"Prefix=%s\n",xmlTextReaderPrefix(reader));
fprintf(stdout,"NamespaceUri=%s\n",xmlTextReaderNamespaceUri(reader));
fprintf(stdout,"BaseUri=%s\n",xmlTextReaderBaseUri(reader));
fprintf(stdout,"Depth=%d\n",xmlTextReaderDepth(reader));
fprintf(stdout,"HasAttributes=%d\n",xmlTextReaderHasAttributes(reader));
fprintf(stdout,"HasValue=%d\n",xmlTextReaderHasValue(reader));
fprintf(stdout,"Value=%s\n",xmlTextReaderValue(reader));
fprintf(stdout,"IsDefault=%d\n",xmlTextReaderIsDefault(reader));
fprintf(stdout,"XmlLang=%s\n",xmlTextReaderXmlLang(reader));
fprintf(stdout,"IsEmptyElement=%d\n",xmlTextReaderIsEmptyElement(reader));
fprintf(stdout,"AttributeCount=%d\n",xmlTextReaderAttributeCount(reader));
}
xmlFreeTextReader(reader);
xmlCleanupParser();
return 0;
}
Here is the code:
#include <stdio.h>
#include <libxml/xmlreader.h>
int main(){
xmlTextReaderPtr reader;
/* initialize libxml2 */
LIBXML_TEST_VERSION
reader = xmlNewTextReaderFilename("my_file.xml");
while ( xmlTextReaderRead(reader) ) {
fprintf(stdout,"ConstName=%s\n",xmlTextReaderConstName(reader));
fprintf(stdout,"LocalName=%s\n",xmlTextReaderLocalName(reader));
fprintf(stdout,"Name=%s\n",xmlTextReaderName(reader));
fprintf(stdout,"NodeType=%d\n",xmlTextReaderNodeType(reader));
fprintf(stdout,"Prefix=%s\n",xmlTextReaderPrefix(reader));
fprintf(stdout,"NamespaceUri=%s\n",xmlTextReaderNamespaceUri(reader));
fprintf(stdout,"BaseUri=%s\n",xmlTextReaderBaseUri(reader));
fprintf(stdout,"Depth=%d\n",xmlTextReaderDepth(reader));
fprintf(stdout,"HasAttributes=%d\n",xmlTextReaderHasAttributes(reader));
fprintf(stdout,"HasValue=%d\n",xmlTextReaderHasValue(reader));
fprintf(stdout,"Value=%s\n",xmlTextReaderValue(reader));
fprintf(stdout,"IsDefault=%d\n",xmlTextReaderIsDefault(reader));
fprintf(stdout,"XmlLang=%s\n",xmlTextReaderXmlLang(reader));
fprintf(stdout,"IsEmptyElement=%d\n",xmlTextReaderIsEmptyElement(reader));
fprintf(stdout,"AttributeCount=%d\n",xmlTextReaderAttributeCount(reader));
}
xmlFreeTextReader(reader);
xmlCleanupParser();
return 0;
}