January 24, 2021
Hot Topics:

Libxml2: Everything You Need in an XML Library

  • By Victor Volkman
  • Send Email »
  • More Articles »

Libxml2 is the XML parser and toolkit written in the C language and is freely available for integration into your apps via the easy-to-digest MIT License. Libxml2 was originally developed for the Gnome project, but doesn't have any dependencies on it or even the Linux platform. This tool is known to be highly portable and is in use by many teams on Linux, Unix, Win32/Win64, Cygwin, MacOS, MacOS/X, and most other platforms, including embedded systems. Even though Libxml2 was written in C, there are an abundance of language bindings available including bindings for Python, Perl, C++, C#, PHP, Pascal, Ruby, and Tcl.

As you know, XML itself is a metalanguage used to design markup languages. That is to say, it is a grammar where semantics and structure are added to the content using extra "markup" information enclosed between angle brackets "<" and ">". HTML certainly is the most well-known markup language and the specification of HTML 4.0 can be fully articulated using an XML Document Type Definition (DTD).

Of course, just saying something is an XML parser doesn't imply all that much. You have to enumerate both how much and what you're going to support. As such, Libxml2 implements a number of existing standards related to markup languages. I won't bore you with the whole laundry list, but the majors are: XML standard 1.0 including Namespaces, Base, URI, XPointer, XInclude, XPath, HTML 4.0 parser, Canonical XML 1.0, XML Schemas Part 2, xml:id, and XML Catalog working drafts. In most cases, libxml2 tries to implement the specifications in a relatively strictly compliant way. Libxml2 has passed all 1800+ tests from the OASIS XML Testsuite.

XML documents aren't always sitting around on your local filesystem for perusal, so Libxml2 includes basic FTP and HTTP clients so you don't have to write an extra layer of code just to find your documents. Libxml2 exports Push (progressive) and Pull (blocking) type parser interfaces for both XML and HTML. Libxml2 can do DTD validation at parse time, using a parsed document instance, or with an arbitrary DTD. Sister projects provide some additional goodies like XSLT 1.0 (from libxslt) and a DOM2 implementation is also in the works.

Let's Get This Parser Started!

Although you are certainly welcome to recompile the source to meet your own project requirement quirks, I found the simplest way to get parsing was through Igor Zlatkovic's dedicated libxml Win32 resource page. In addition to DLL downloads, you will also find C#, Perl (Apache), and Pascal language bindings at the bottom of Zlatkovic's page. Zlatkovic has packaged Libxml2 and related tools so you can simply take the subset you really need:

  • libxml2, the XML parser and processor
  • libxslt, the XSL and EXSL Transformations processor
  • xmlsec, the XMLSec and XMLDSig processor
  • xsldbg, the XSL Transformations debugger
  • openssl, the general crypto toolkit
  • iconv, the character encoding toolkit
  • zlib, the compression toolkit

Figure 1: libxml package dependencies

For example, libxml depends on iconv and zlib. If you run the included xmllint.exe or xmlcatalog.exe, you simply will discover that you need iconv.dll (as promised in the dependency chart). Be advised that Zlatkovic's downloads don't include the sample programs and data files, however.

For purposes of this article, I used Zlatkovic's distribution of libxml2 2.6.30+, iconv 1.9.2., and zlib 1.2.3.

How to Parse a Tree with Libxml2

You'll only look at the Document Object Model (DOM) parser because that is inherently more complex than the Simple API for XML (SAX). As you recall, the DOM model gives you complete tree navigation at the cost of maintaining the whole XML file in memory. If you're not modifying the tree as it's being parsed, SAX can be significantly less overhead.

Click here for a larger image.

Figure 2: DOM tree example

Specifically, you'll dissect the tree1.c example program and identify some common programming paradigms used. The purpose of this program is to parse a file to a tree, use xmlDocGetRootElement() to get the root element, and then walk the document and print all the element names in document order. This is about the easiest non-trivial sort of thing you can do in XML. For simplicity's sake, you'll assume that the XML file you want to parse is the first argument on the command line and output will go to stdout (console). Program listing follows:

 1 #include <stdio.h>
 2 #include <libxml/parser.h>
 3 #include <libxml/tree.h>
 5 static void print_element_names(xmlNode * a_node)
 6 {
 7    xmlNode *cur_node = NULL;
 9    for (cur_node = a_node; cur_node; cur_node =
         cur_node->next) {
10       if (cur_node->type == XML_ELEMENT_NODE) {
11          printf("node type: Element, name: %s\n",
12       }
13       print_element_names(cur_node->children);
14    }
15 }
17 int main(int argc, char **argv)
18 {
19    xmlDoc *doc = NULL;
20    xmlNode *root_element = NULL;
22    if (argc != 2)  return(1);
24    LIBXML_TEST_VERSION    // Macro to check API for match with
                             // the DLL we are using
26    /*parse the file and get the DOM */
27    if (doc = xmlReadFile(argv[1], NULL, 0)) == NULL){
28       printf("error: could not parse file %s\n", argv[1]);
29       exit(-1);
30       }
32    /*Get the root element node */
33    root_element = xmlDocGetRootElement(doc);
34    print_element_names(root_element);
35    xmlFreeDoc(doc);       // free document
36    xmlCleanupParser();    // Free globals
37    return 0;
38 }

Page 1 of 2

This article was originally published on February 25, 2008

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date