C# - 如何从XElement中删除xmlns

Edu*_*rdo 6 c# xml linq xelement

如何从XElement中删除"xmlns"命名空间?

我试过:attributes.remove,xElement.Name.NameSpace.Remove(0)等等.没有成功.

我的xml:

<event xmlns="http://www.blablabla.com/bla" version="1.00">
  <retEvent version="1.00">
  </retEvent>
</event>
Run Code Online (Sandbox Code Playgroud)

我怎么能做到这一点?

Hey*_*ude 8

我想扩展现有的答案。具体来说,我想参考一个从 中删除命名空间的常见用例XElement,即:能够以通常的方式使用 Linq 查询。

当标签包含命名空间时,必须将此命名空间用作XNamespace每个 Linq 查询(如本答案中所述),以便使用 OP 的 xml,它将是:

XNamespace ns = "http://www.blablabla.com/bla";
var element = xelement.Descendants(ns + "retEvent")).Single();
Run Code Online (Sandbox Code Playgroud)

但通常情况下,我们不想每次都使用这个命名空间。所以我们需要删除它。

现在,@octaviocc 的建议确实从给定元素中删除了命名空间属性。但是,元素名称仍包含该 namespace,因此通常的 Linq 查询将不起作用。

Console.WriteLine(xelement.Attributes().Count()); // prints 1
xelement.Attributes().Where( e => e.IsNamespaceDeclaration).Remove();
Console.WriteLine(xelement.Attributes().Count()); // prints 0
Console.WriteLine(xelement.Name.Namespace); // prints "http://www.blablabla.com/bla"
XNamespace ns = "http://www.blablabla.com/bla";
var element1 = xelement.Descendants(ns + "retEvent")).SingleOrDefault(); // works
var element2 = xelement.Descendants("retEvent")).SingleOrDefault();      // returns null
Run Code Online (Sandbox Code Playgroud)

因此,我们需要使用@Sam Shiles 建议,但可以简化(无需递归):

private static void RemoveAllNamespaces(XElement xElement)
{
    foreach (var node in xElement.DescendantsAndSelf())
    {
        node.Name = node.Name.LocalName;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果需要使用一个XDocument

private static void RemoveAllNamespaces(XDocument xDoc)
{
    foreach (var node in xDoc.Root.DescendantsAndSelf())
    {
        node.Name = node.Name.LocalName;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在它起作用了:

var element = xelement.Descendants("retEvent")).SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)


Sam*_*les 7

接受的答案对我不起作用,因为xelement.Attributes()它是空的,它没有将命名空间作为属性返回.

以下将删除您案例中的声明:

element.Name = element.Name.LocalName;

如果要以递归方式为元素执行此操作,并且所有子元素都使用以下内容:

    private static void RemoveAllNamespaces(XElement element)
    {
        element.Name = element.Name.LocalName;

        foreach (var node in element.DescendantNodes())
        {
            var xElement = node as XElement;
            if (xElement != null)
            {
                RemoveAllNamespaces(xElement);
            }
        }
    } 
Run Code Online (Sandbox Code Playgroud)

  • 不断收到错误:无法将前缀 '' 从 '' 重新定义到同一起始元素标记内。只是对现有文档中的一个元素使用了简单的形式,无论我尝试从文档中单独复制该元素,然后使用“element.Name = element.Name.LocalName;” 并将其附加到文档中,不断出现错误,只有在我尝试了在互联网上找到的所有该死的东西后,其他答案才起作用 (3认同)

oct*_*ccl 6

您可以使用IsNamespaceDeclaration检测哪个属性是名称空间

xelement.Attributes()
        .Where( e => e.IsNamespaceDeclaration)
        .Remove();
Run Code Online (Sandbox Code Playgroud)

  • @octavioccl没有任何反应。xelement在Attributes(“ xmlns”)。Remove()前后是相同的 (2认同)