Libxml
Inhaltsverzeichnis
XML-Dateien erzeugen
#include <libxml/tree.h>
#include <stdio.h>
int
main(void)
{
xmlDoc *doc = xmlNewDoc("1.0");
if(! doc) {
fprintf(stderr, "unable to allocate new xml document");
return 1;
}
xmlNs *ns = xmlNewNs(NULL, "http://brokenpipe.de/", "bpipe");
if(! ns) {
fprintf(stderr, "unable to register own namespace");
return 1;
}
xmlNode *root = xmlNewNode(ns, "rootnode");
if(! root) {
fprintf(stderr, "unable to allocate future root node");
return 1;
}
/* write out xmlns:bpipe= declarator on root node */
root->nsDef = ns;
xmlDocSetRootElement(doc, root);
xmlNode *childnode = xmlNewChild(root, ns, "child", "blablub");
if(! childnode) {
fprintf(stderr, "unable to allocate child node");
return 1;
}
xmlNewProp(childnode, "content", "text");
xmlNewProp(childnode, "foo", "bar");
if(! xmlNewChild(childnode, ns, "text", "inhalt")) {
fprintf(stderr, "unable to allocate text sub-node");
return 1;
}
xmlSaveFormatFile("-", doc, 1);
return 0;
}
obenstehendes Programm sollte folgende Ausgabe von sich geben:
<?xml version="1.0"?> <bpipe:rootnode xmlns:bpipe="http://brokenpipe.de/"> <bpipe:child content="text" foo="bar">blablub<bpipe:text>inhalt</bpipe:text></bpipe:child> </bpipe:rootnode>
Elemente wieder lesen
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include <libxml/parser.h>
#include <stdio.h>
int
main(void)
{
xmlDoc *doc = xmlParseFile("zerties.xml");
if(! doc) {
fprintf(stderr, "unable to read input file\n");
return 1;
}
xmlXPathInit();
xmlXPathContext *ctx = xmlXPathNewContext(doc);
if(! ctx) {
fprintf(stderr, "unable to create context\n");
return 1;
}
xmlXPathRegisterNs(ctx, "bpipe", "http://brokenpipe.de/");
const xmlChar *xpath_expr = "/bpipe:rootnode/bpipe:child/bpipe:text/text()";
xmlXPathObject *obj = xmlXPathEvalExpression(xpath_expr, ctx);
if(! obj) {
fprintf(stderr, "xmlXPathEvalExpression call failed.\n");
return 1;
}
printf("Ergebnis: %s\n", xmlXPathCastToString(obj));
return 0;
}
Abfrage von Attributen
Selbstverständlich können mit XPath auch Attribute abgefragt werden. Um zum Beispielt das Attribut foo aus dem obenstehend abgedruckten XML-File zu extrahieren, ist folgende XPath-Expression zu verwenden:
const xmlChar *xpath_expr = "/bpipe:rootnode/bpipe:child/@foo";
Anstelle von @foo kann auch attribute::foo verwendet werden. Achtung, zwei Doppelpunkte, ansonsten würde es sich um den Namespace attribute handeln...
Weiterführende Informationen zum Thema XPath findet ihr hier: XPath Tutorial des W3C
Compilen ...
CFLAGS="`xml2-config --cflags` -Wall -W -ggdb" LDFLAGS="`xml2-config --libs`"