libxml: C program to open and close an XML file
To read an xml file, you can make use of the libxml library. The following program introduces the functions to open and close an xml file.
We introduce here the following functions:
- xmlNewTextReaderFilename
- xmlTextReaderClose
We also make use of the following structure
- xmlTextReaderPtr
xmlTextReaderPtr: Let’s start with xmlTextReaderPtr. This is a pointer to the structure pertaining to the xml Text Reader. The structure is internally used by the libxml library. A pointer structure is returned from various functions related to creating a reader for XML file or in-memory XML file.
xmlNewTextReaderFilename: This creates a reader when we supply with the URI of the file or resource to be read. The URI is the absolute path of an xml file. This functions returns a xmlTextReaderPtr.
Following is the syntax of xmlNewTextReaderFilename
xmlTextReaderPtr xmlNewTextReaderFilename (const char * URI)
xmlTextReaderClose: This function releases all the resources taken up by the reader. It takes as input the xmlTextReaderPtr
The following program depicts how to make use of the above discussed functions and structures
#include <stdio.h>
#include <stdlib.h>
#include <libxml/xmlreader.h>
int main(int argc, char *argv[])
{
xmlTextReaderPtr reader;
if (argc != 2) {
printf("xmlreader filename.xml\n");
exit(0);
}
reader = xmlNewTextReaderFilename(argv[1]);
if(!reader) {
perror(" xmlTextReaderPtr:");
exit(0);
}
xmlTextReaderClose(reader);
}
$ gcc xmlreader.c `xml2-config --cflags --libs` -o xmlreader
To execute the file, we must supply the absolute path of a sample xml file
$ ./xmlreader /home/user/book.xml
This program does not perform any special operation, but depicts how to open and close an XML file using libxml functions
Comments: