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 thoughts on “Parsing Xml with C#

  1. Pingback: Parsing XHTML with C# « devioblog

  2. Pingback: Introducing graspx « devioblog

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 )

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.