如何在C#中删除每个XML元素中的“xmlns:…”名称空间信息?
如何在C#中删除每个XML元素中的“xmlns:…”名称空间信息?
除了Zombiesheep的谨慎回答外,我的解决方法是使用XSLT转换来清除XML中的这些内容。
wash.xsl:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no" encoding="UTF-8"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
请点击此处http://simoncropp.com/working-around-xml-namespaces,了解如何解决XML命名空间问题。
var xDocument = XDocument.Parse(
@"<root>
<f:table xmlns:f=""http://www.w3schools.com/furniture"">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>");
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
对象之前,我进行了文本替换以删除有问题的命名空间属性。一开始感觉不对,因为最终得到的XML无法由Visual Studio中的“XML Visualizer”解析。这最初让我放弃了这种方法。
然而,仍然可以将文本加载到XmlDocument
中,并且可以将其输出到BizTalk中。
还要注意,早些时候,当尝试使用childNode.Attributes.RemoveAll()
删除命名空间属性时,我陷入了困境-它只是再次出现了!