Thursday, March 01, 2012

Back to XmlDomDocument

While we are all moving along to LINQ and other ways to parse XML, I got stuck doing my first pass with the old System.Xml classes. So I needed to solve this problem with parsing when you have many varied namespaces in the data.

Here is my Twitter client code :


WebClient Client = new WebClient();

Stream stream =
Client.OpenRead("http://search.twitter.com/search.atom?q=" +
txtSearchVal.Text);

StreamReader reader = new StreamReader(stream);
XmlDocument doc = new XmlDocument();

string fullResponse = reader.ReadToEnd();
doc.LoadXml(fullResponse);

XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);

mgr.AddNamespace("google", "http://base.google.com/ns/1.0");
mgr.AddNamespace("openSearch", "http://a9.com/-/spec/opensearch/1.1/");
mgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
mgr.AddNamespace("twitter", "http://api.twitter.com/");
mgr.AddNamespace("georss", "http://www.georss.org/georss");

txtAllXML.Text = doc.OuterXml;

XmlNodeList list = doc.SelectNodes("//atom:entry", mgr);
foreach (XmlNode node in list)
{
listView1.Items.Add(
new ListViewItem() {
Text = node.SelectSingleNode("atom:title", mgr).InnerText })
.SubItems
.AddRange(new string[] {
node.SelectSingleNode("atom:author", mgr).InnerText,
node.SelectSingleNode("atom:content", mgr).InnerText
}
);
}



I had to add the "atom" prefix as no prefix was supplied by the data.