Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an XmlNode object ignoring undeclared namespaces?

Tags:

c#

.net

xml

xmlnode

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?

like image 912
John K Avatar asked Oct 28 '10 03:10

John K


1 Answers

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;
}
like image 162
dahlbyk Avatar answered Oct 05 '22 16:10

dahlbyk