{STATIC} hippo

...on becoming a great developer...
MCTS: .NET Framework 3.5, ASP.NET Applications
posts - 29, comments - 6, trackbacks - 0

My Links

Twitter

Archives

Post Categories

Thursday, December 03, 2009

.NET, XPath, and XmlNamespaceManager

Take the following XML fragment

   1: <?xml version="1.0" encoding="iso-8859-1"?>
   2: <con:search-results 
   3: xmlns:con="http://namespace.contoso.com/business-objects" 
   4: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   5: xsi:noNamespaceSchemaLocation="http://www.contoso.com/dtd/syndication/biz-objects.xsd">
   6:     <con:search-query>ipod</con:search-query>
   7:     <con:result-count>2207</con:result-count>
   8:     <con:start-index>0</con:start-index>
   9:     <con:result-count>15</con:result-count>
  10:     <con:results>
  11:         <con:result>
  12:             ...
  13:             

Now suppose you loaded this XML into an XmlDocument, how would you query for all the <con:result> nodes?  Using XPath you’d write something like

   1: /search-results/results/result

So you might try writing something like

   1: XmlDocument doc = new XmlDocument();
   2: doc.LoadXml(response);
   3: var resultNodes = doc.SelectNodes("/search-results/results/result");

but you would find that resuldNodes would be null.  You have to instantiate an XmlNamespaceManager to help correctly maneuver your namespaces.  That’s done like so:

   1: XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
   2: nsmgr.AddNamespace("con", "http://namespace.contoso.com/business-objects");

Then you would query your xml like so:

   1: var resultNodes = doc.SelectNodes("/con:search-results/con:results/con:result")

That took me a little searching to dig up, but it makes sense, right?

posted @ Thursday, December 03, 2009 2:16 PM | Feedback (0) | Filed Under [ c# XML ]

Gunnar Optiks glasses update

All I can say is I love my Gunnar Optiks Rx computer glasses.  My whole body just feels better at the end of the day and I have a lot less sensitivity to light at 10pm.  In general, during my day, I concentrate more and lose myself in my work more since I got these glasses.  I highly recommend them to everyone who spends most of their day in front of a computer monitor.

posted @ Thursday, December 03, 2009 1:55 PM | Feedback (0) | Filed Under [ Misc ]

Powered by: