如何加载 XmlNode 对象忽略未声明的命名空间?

发布于 2024-09-29 15:43:58 字数 1025 浏览 0 评论 0原文

我想加载 XmlNode 而不获取 <当存在无法识别的命名空间时,出现 href="http://msdn.microsoft.com/en-us/library/system.xml.xmlexception.aspx" rel="noreferrer">XmlException。

原因是因为我需要将 XMLNode 实例传递给方法。我正在加载具有脱离其原始上下文的名称空间的任意 XML 片段(例如,MSWord 格式和具有各种模式的其他软件产品,这些模式会使用其名称空间前缀“污染”内容)。命名空间对我或它所传递到的目标方法并不重要。 (这是因为目标方法将其用作 HTML 进行渲染,命名空间将自然被忽略或抑制。)

示例
下面是我尝试制作 XMLNode 的示例片段:

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

当我尝试将其加载到 XmlDocument 实例(这是我获取 XmlNode 的尝试)我收到以下 XML 异常:

'st1' 是未声明的命名空间。第 3 行,位置 251。

如何从此类 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许仙没带伞 2024-10-06 15:43:58

XmlTextReader 有一个 Namespaces 属性,您可以关闭:

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

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文