Thursday
6
Mar 2008

Tango XML - Querying the weather in London

(5:42 pm) Tags: [General, Projects, D Programming Language]

I was helping someone on IRC in #d.tango try to use tango.text.xml to parse and display data from an xml document. We ended up building a simple example using HttpGet to get the document, Document to parse it, and Document’s xpath-like querying functionality to extract the useful bits.

import tango.io.File;
import tango.io.Stdout;
import tango.text.xml.Document;
import tango.net.http.HttpGet;
void main ()
{
        auto doc = new Document!(char);
        auto page = new HttpGet (\"http://www.google.com/ig/api?weather=London\");
        auto content = cast (char[]) page.read;
	doc.parse (content);
	foreach( node; doc.query.descendant[\"forecast_conditions\"])
	{
	  Stdout.formatln(\"forecast for {} is {} with a high of {}\",
			  node.query[\"day_of_week\"].attribute.nodes[0].value,
			  node.query[\"condition\"].nodes[0].getAttribute(\"data\").value,
			  node.query[\"high\"].nodes[0].getAttribute(\"data\").value);
	}
}

The D programming language coupled with Tango as a standard library allows you to become a productive programmer.

Update: Please ignore the backslashes in the code if you are trying to run this example. For some reason, Wordpress is mucking around with the output.

Popularity: 7%

Leave a Reply