tags:

views:

32

answers:

1

I want to load up an XmlNode without getting an XmlException when an unrecognized namespace is present.

The reason is because I need to pass an XMLNode instance to a method. I'm loading up arbitrary XML fragments having namespaces out of their original context (e.g. MSWord formatting and other software products with various schemas that "pollute" the content with their namespace prefixes). The namespaces are not important to me or to the target method to which it's passed. (This is because the target method uses it as HTML for rendering and namespaces will be ignored or suppressed naturally.)

Example
Here's an example fragment I'm trying to make an XMLNode out of:

 <p>
 <div>
     <st1:country-region w:st="on">
     <st1:place w:st="on">Canada</st1:place>
     </st1:country-region>
     <hr />
     <img src="xxy.jpg" />
 </div>
 </p>

When I try to load it into an XmlDocument instance (that's my attempt to get an XmlNode) I get the following XML Exception:

'st1' is an undeclared namespace. Line 3, position 251.

How do I go about getting an XmlNode instance from that kind of XML fragment?

+2  A: 

XmlTextReader has a Namespaces property you can turn off:

XmlDocument GetXmlDocumentFromString(string xml) {
    var doc = new XmlDocument();

    using (var sr = new StringReader(xml))
    using (var xtr = new XmlTextReader(sr) { Namespaces = false })
        doc.Load(xtr);

    return doc;
}
dahlbyk
Thank you. That meets the need and is very simple.
John K