Overview
libxml2 is the reference XML/HTML parser — used by GNOME, Python's lxml, PHP, and countless production systems. It offers full XML 1.0/1.1, namespaces, DTD and XSD validation, XPath 1.0 queries, and a complete DOM API for building and modifying XML trees.
CLib package
Ubuntu/Debian: sudo apt install libxml2-dev
Parse & Navigate
uses libxml2;
var xml := '<catalog><book id="1"><title>PascalAI</title><price>29.99</price></book></catalog>';
var doc := ParseString(xml);
var root := RootElement(doc);
WriteLn('Root: ', NodeName(root)); // "catalog"
var books := ChildrenByTag(root, 'book');
for I := 0 to Length(books) - 1 do begin
var book := books[I];
WriteLn('id: ', GetAttr(book, 'id'));
WriteLn('title: ', NodeText(FirstChild(book, 'title')));
WriteLn('price: ', NodeText(FirstChild(book, 'price')));
end;
FreeDoc(doc);
XPath Queries
var doc := ParseFile('/data/catalog.xml');
// Select all book titles
var titles := XPath(doc, '//book/title');
for I := 0 to Length(titles) - 1 do
WriteLn(NodeText(titles[I]));
// Select books with price < 30
var cheap := XPath(doc, '//book[price < 30]');
WriteLn('Cheap books: ', Length(cheap));
// Single string value
var first := XPathString(doc, '//book[1]/title');
WriteLn('First title: ', first);
// Count
var n := XPathNumber(doc, 'count(//book)');
WriteLn('Total books: ', Round(n));
FreeDoc(doc);
Parse HTML
// Parse real-world HTML (lenient — tolerates unclosed tags, etc.)
var doc := ParseHTMLFile('/web/page.html');
var links := XPath(doc, '//a[@href]');
for I := 0 to Length(links) - 1 do
WriteLn(GetAttr(links[I], 'href'), ' — ', NodeText(links[I]));
FreeDoc(doc);
Build XML
var doc := NewDoc('report');
var root := RootElement(doc);
SetAttr(root, 'version', '1.0');
var section := AddChild(root, 'section');
SetAttr(section, 'name', 'results');
var item := AddChild(section, 'item');
SetText(item, 'Passed');
SetAttr(item, 'id', '42');
WriteLn(ToPrettyString(doc));
SaveToFile(doc, '/out/report.xml');
FreeDoc(doc);
Namespaces & Validation
// XPath with namespace prefixes
var nodes := XPathNS(doc, '//soap:Body/m:GetPrice',
'soap=http://schemas.xmlsoap.org/soap/envelope/' + #10 +
'm=http://example.com/prices');
// Validate against XSD schema
if ValidateXSD(doc, '/schemas/catalog.xsd') then
WriteLn('Valid!')
else
WriteLn('Invalid: ', LastError);
// Check well-formedness
if not IsWellFormed(xmlString) then
WriteLn('Malformed XML');
Package Info
Version1.0.0
Typeclib
C Librarylibxml2
Authorgustavo
Functions
- ParseString / ParseFile
- ParseHTML / ParseHTMLFile
- FreeDoc / LastError
- ToString / ToPrettyString
- SaveToFile
- RootElement
- NodeName / NodeText
- GetAttr / SetAttr / HasAttr
- AttrNames / RemoveAttr
- Children / FirstChild
- ChildrenByTag
- Parent / NextSibling / PrevSibling
- XPath / XPathFrom
- XPathString / XPathNumber
- XPathNS
- NewDoc / AddChild
- SetText / RemoveNode
- ValidateDTD / ValidateXSD
- IsWellFormed
- XML2Version
See Also
- libxslt (transforms)
- xml-parser (PAI)
- json-parser