libxml: C program to open and close an XML file

Posted by Joys of Programming on in C/C++

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:

  1. xmlNewTextReaderFilename
  2. xmlTextReaderClose

We also make use of the following structure

  1. 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);
}

To compile the above program,


$ 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

Tags: , , , , ,

Comments:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2009-2012 Joys of Programming All rights reserved.
Desk Mess Mirrored v1.8.1 theme from BuyNowShop.com.