What it is
libxml2 is a C library for parsing XML documents. It provides a comprehensive set of functions for reading, validating, navigating, and manipulating XML data efficiently, and supports standards like XPath, XInclude, and XPointer.
libxml2 allows developers to parse XML documents either in memory or from files, traverse XML trees, extract information with XPath, validate against DTD or XML Schema, and modify XML content programmatically.
Installation
sudo apt install libxml2-devGetting started
The smallest useful thing you can do with it, and what each part means.
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <stdio.h>
int main() {
xmlDoc *doc = xmlReadFile("example.xml", NULL, 0);
if (doc == NULL) {
printf("Failed to parse XML\n");
return 1;
}
xmlFreeDoc(doc);
xmlCleanupParser();
return 0;
}xmlNode *root = xmlDocGetRootElement(doc);
printf("Root element: %s\n", root->name);Advanced usage
Where the library earns its place over a simpler alternative.
for(xmlNode *node = root->children; node; node = node->next) {
if(node->type == XML_ELEMENT_NODE)
printf("Node name: %s\n", node->name);
}#include <libxml/xpath.h>
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression((xmlChar*)"//book", xpathCtx);
for(int i=0; i < xpathObj->nodesetval->nodeNr; i++) {
xmlNodePtr node = xpathObj->nodesetval->nodeTab[i];
printf("Book node: %s\n", node->name);
}
xmlXPathFreeObject(xpathObj);
xmlXPathFreeContext(xpathCtx);xmlNodePtr newNode = xmlNewChild(root, NULL, (xmlChar*)"author", (xmlChar*)"John Doe");xmlValidCtxtPtr ctxt = xmlNewValidCtxt();
int ret = xmlValidateDocument(ctxt, doc);
xmlFreeValidCtxt(ctxt);Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- xmlReadFile returns NULL
- Check that the file exists, is readable, and contains valid XML.
- Invalid XPath expression
- Ensure the XPath syntax is correct and matches the XML structure.
- Memory leaks
- Always free documents, nodes, and contexts after use.
Best practices
- Always call `xmlCleanupParser()` before exiting to release memory.
- Check return values when parsing or modifying XML to handle errors.
- Use UTF-8 encoding for XML strings to avoid character issues.
- Free documents with `xmlFreeDoc()` after use to prevent memory leaks.
- Use XPath for efficient element selection instead of manual tree traversal.
Background
Why it exists, and what it was reacting to.
libxml2 was developed as part of the GNOME project and has become the standard library for XML parsing in C applications. It is widely used in software ranging from desktop applications to web services that require robust XML processing.
