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

Mar*_*arc 10 .net c# xml namespaces

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

ann*_*ata 10

虽然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>
Run Code Online (Sandbox Code Playgroud)

  • @Dimitre - 多么令人难以置信的冒犯.如果你想带来一些有价值的东西,也许你可以支持断言这将是破坏性的,而不是攻击不言而喻的(即这个问题存在)事实,名称空间可能是一个问题."干杯"给你白痴. (7认同)

Sim*_*mon 6

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

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));
    }
}
Run Code Online (Sandbox Code Playgroud)