Thursday 25 October 2012

Processing xml fragments which include namespaces in C#

Recently I needed to process an xml fragment using .Net's XmlReader class. This worked fine until the fragment contained a reference to a namespace when it started throwing undeclared namespace exceptions. In my case the namespace was xmlmime which is not included in the default namespace manager.

After searching the web for examples I found that there was a general lack of examples which use XmlReader. Mostly they use XmlTextReader which for various reasons I was unable to use in the project I was working on. Below is an example snippet of code which show how to overcome the undeclared namespace exception I was getting when trying to read the fragment.

byte[] xmlBytes = System.Text.Encoding.UTF8.GetBytes(xmlString);
MemoryStream stream = new MemoryStream(xmlBytes, false);

// Create the namespace required to process configuration xml objects
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("xmlmime", "http://www.w3.org/2004/11/xmlmime");
namespaceManager.AddNamespace("another", "urn:something");

// Create the context required to parse configuration fragments
var context = new XmlParserContext(null, namespaceManager, null, XmlSpace.Default);

// Create the xml reader with the required context to parse a configuration object
var xmlReader = XmlReader.Create(stream, null, context);

while (xmlReader.Read())
{
 switch (xmlReader.NodeType)
 {
  case XmlNodeType.Element:
   // process element
   break;
 }
}