更新时间:2023-12-03 21:34:58
因为你要在整个XML文档中替换它我会去找这个简单易读的方法:
Since you're replacing it in the entire XML document I'd go for this simple and readable approach:
using System.Xml;
using System.Text.RegularExpressions;
public static class XMLExtensions
{
public static void RemoveNamespace(this XmlDocument document, string @namespace) =>
document.InnerXml = Regex.Replace(
document.InnerXml,
@ (?< = \< / | \<){@ namespace}:,
);
}
@"(?<=\</|\<){@namespace}:", ""); }
编辑:如果某些数据被命名为APCS,则更改正则表达式以仅捕获标记中的名称空间。非贪婪默认设置的小修复。
EDIT2:xmlns命名空间通常只包含一次,但如果你需要以编程方式删除它,这将是这样做:
Changed regex to catch only namespaces in tags in case some data is named APCS. Small fix in case of a non-greedy default setting.
The xmlns namespace is usually only included once but if you need to programmatically remove it as well this will do it:
using System.Xml;
using System.Text.RegularExpressions;
public static class XMLExtensions
{
public static void RemoveNamespace(this XmlDocument document, string @namespace) =>
document.InnerXml = Regex.Replace(
document.InnerXml,
@ ((?< = \< / | \<){@ namespace}:| xmlns:{@ namespace} = [^] +),
);
}
@"((?<=\</|\<){@namespace}:|xmlns:{@namespace}=""[^""]+"")", ""); }