Parsing Xml with C#

I tried to load the source code of an .aspx page as an XmlDocument, but immediately ran into the XmlException “asp is an undeclared namespace”.

So I tried to figure out different ways of declaring namespaces for XmlReader or XmlTextReader, but no matter how I tried to convince the XmlNamespaceManager to accept the asp namespace, I always ended up with this error message.

Until I came across XmlParserContext.

My code now looks like this:

XmlDocument doc = new XmlDocument();
NameTable nt = new NameTable();
XmlNamespaceManager mgr = new XmlNamespaceManager(nt);
mgr.AddNamespace("asp", "urn:asp");
  XmlParserContext xpc = new XmlParserContext(
  nt, mgr, "", XmlSpace.Default);
XmlTextReader rdt = new XmlTextReader(
  "<aspx>" + sb.ToString() + "</aspx>",
  // sb is a StringBuilder containing the preprocessed aspx
  XmlNodeType.Element, xpc);

and it works!


2 Responses to Parsing Xml with C#

  1. […] XHTML with C# In my previous post I described how to load XML documents containing undeclared […]

  2. […] have previously written about parsing XML/XHTML files with C# here and […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: