C#:如何从XML元素中删除命名空间信息

如何从C#中的每个XML元素中删除“xmlns:…”命名空间信息?

虽然Zombiesheep的警示答案,我的解决方案是使用xslt转换来清洗xml来执行此操作。

wash.xsl:

                  

从这里http://simoncropp.com/working-around-xml-namespaces

 var xDocument = XDocument.Parse( @"  African Coffee Table 80 120  "); xDocument.StripNamespace(); var tables = xDocument.Descendants("table"); public static class XmlExtensions { public static void StripNamespace(this XDocument document) { if (document.Root == null) { return; } foreach (var element in document.Root.DescendantsAndSelf()) { element.Name = element.Name.LocalName; element.ReplaceAttributes(GetAttributes(element)); } } static IEnumerable GetAttributes(XElement xElement) { return xElement.Attributes() .Where(x => !x.IsNamespaceDeclaration) .Select(x => new XAttribute(x.Name.LocalName, x.Value)); } } 

我有一个类似的问题(需要从特定元素中删除命名空间属性,然后将XML作为XmlDocument返回到BizTalk),但这是一个奇怪的解决方案。

在将XML字符串加载到XmlDocument对象之前,我进行了文本替换以删除有问题的命名空间属性。 一开始看起来似乎错了,因为我最终得到了无法通过Visual Studio中的“XML Visualizer”解析的XML。 这是最初让我摆脱这种方法的原因。

但是,文本仍然可以加载到XmlDocument ,我可以将它输出到BizTalk罚款。

还要注意,之前我在尝试使用childNode.Attributes.RemoveAll()删除命名空间属性时遇到了一条死胡同 – 它又回来了!