【问题标题】:C#: How to remove namespace information from XML elementsC#:如何从 XML 元素中删除命名空间信息
【发布时间】:2010-09-29 14:36:03
【问题描述】:

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

【问题讨论】:

  • 您是否要获取文件,替换文本并重新保存?
  • 不,我收到了字符串格式的 XML,必须将其转换为 HTML(仍然是字符串格式)。

标签: c# .net xml namespaces


【解决方案1】:

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

【讨论】:

  • 非常感谢您。这正是我一直在寻找的:现在我首先使用这个 XSL 转换 XML,然后将我的 XSL 应用到输出。你拯救了我的一天!
  • @Dimitre - 令人难以置信的冒犯。如果您想为表带来一些有价值的东西,也许您可​​以支持这样的断言,即这将是破坏性的,而不是攻击名称空间可能是一个问题这一不言而喻的事实(即这个问题存在)。白痴“干杯”。
  • 很棒的帖子 anakata :] 谢谢!
【解决方案2】:

从这里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));
    }
}

【讨论】:

    【解决方案3】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-06
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      相关资源
      最近更新 更多