How to load an XmlNode object ignoring undeclared namespaces?

前提是你 提交于 2019-12-03 16:34:24

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/4039464/how-to-load-an-xmlnode-object-ignoring-undeclared-namespaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!