Friday, May 9, 2008

Accessing XML Elements with Namespaces using the ASP.NET XPathNavigator

If you need to access XML elements that have a namespace associated with them using the XPathNavigator object, here's how you can create an XmlNamespaceManager and use it. This is part of a bit of code where I was processing an RSS post.

StringBuilder myString = new StringBuilder();
XPathDocument myDoc = new XPathDocument(myDocumentUri);
XPathNavigator myNav = myDoc.CreateNavigator();
XmlNamespaceManager myManager = new XmlNamespaceManager(myNav.NameTable);
// Here you add the name and URI for all the namespaces you need to handle.
myManager.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
myManager.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");

XPathNodeIterator myPosts = myNav.Select("//post");
if (myPosts.Count > 0)
{
while (myPosts.MoveNext())
{
// Add the post author.
// You're passing the XmlNamespaceManager to SelectSingleNode
XPathNavigator author = myPosts.Current.SelectSingleNode(
"descendant::dc:creator[1]", myManager);
if (author != null)
myString.AppendLine("by " + author.ToString());
}
}

No comments: