dinsdag 27 mei 2008

XmlPatterns 101

Just this month Qt4.4 was released. Amongst the hot new stuff is QtXmlPatterns, which packs a C++ XQuery API. XQuery is a full blown typed XML query language based on XPath combined with so called FLOWR expressions [for-let-where-orderby-return]. While it's main goal is XML transformation one can abuse it as an ultra concise parser. Let's see a small example.

<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<suite name="suite1" dir="/a/b">
<case name="test1" exe="t.sh">
<command name="cmd11" />
<command name="cmd12" />
</case>
<case name="test2" exe="t2.sh">
<command name="cmd21" />
</case>
</suite>
</root>


Say we want to extract dir, exe and name for each command in the listing above. This can be done in just four lines of XQuery, quite economic compared to your average dom-traversal code.

    QXmlQuery query;
query.setQuery(
"for $suite in doc(\"test.xml\")//suite\n"
"for $case in $suite/case\n"
"for $cmd in $case/command\n"
"return concat($suite/@dir, '/', $case/@exe, ' ', $cmd/@name)\n");
QStringList cmds;
query.evaluateTo(&cmds);


At this point the 'cmds' QStringList contains:
("/a/b/t.sh cmd11", "/a/b/t.sh cmd12", "/a/b/t2.sh cmd21")

Geen opmerkingen: