首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何删除XDocument中根以外节点的xmlns属性?

如何删除XDocument中根以外节点的xmlns属性?
EN

Stack Overflow用户
提问于 2014-06-19 19:42:21
回答 2查看 52.9K关注 0票数 23

情况

我正在使用XDocument尝试删除第一个内部节点上的xmlns=""属性:

代码语言:javascript
复制
<Root xmlns="http://my.namespace">
    <Firstelement xmlns="">
        <RestOfTheDocument />
    </Firstelement>
</Root>

因此,我想要的结果是:

代码语言:javascript
复制
<Root xmlns="http://my.namespace">
    <Firstelement>
        <RestOfTheDocument />
    </Firstelement>
</Root>

代码

代码语言:javascript
复制
doc = XDocument.Load(XmlReader.Create(inStream));

XElement inner = doc.XPathSelectElement("/*/*[1]");
if (inner != null)
{
    inner.Attribute("xmlns").Remove();
}

MemoryStream outStream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(outStream);
doc.Save(writer); // <--- Exception occurs here

问题

在尝试保存文档时,我得到以下异常:

不能在同一开始元素标记内将前缀'‘从'’重新定义为'http://my.namespace‘。

这到底是什么意思,我该怎么做才能移除那个讨厌的xmlns=""呢?

备注

  • I确实希望保留根节点的namespace
  • I,只希望删除该特定的xmlns,则文档中将不会有其他xmlns属性。

更新

我曾尝试使用受this question答案启发的代码

代码语言:javascript
复制
inner = new XElement(inner.Name.LocalName, inner.Elements());

在调试时,xmlns属性从其中消失了,但我得到了相同的异常。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-06-19 22:37:10

我认为下面的代码就是你想要的。您需要将每个元素放入正确的名称空间,并删除受影响元素的所有xmlns=''属性。后面的部分是必需的,否则LINQ to XML基本上会给您留下一个

代码语言:javascript
复制
<!-- This would be invalid -->
<Firstelement xmlns="" xmlns="http://my.namespace">

代码如下:

代码语言:javascript
复制
using System;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XDocument doc = XDocument.Load("test.xml");
        // All elements with an empty namespace...
        foreach (var node in doc.Root.Descendants()
                                .Where(n => n.Name.NamespaceName == ""))
        {
             // Remove the xmlns='' attribute. Note the use of
             // Attributes rather than Attribute, in case the
             // attribute doesn't exist (which it might not if we'd
             // created the document "manually" instead of loading
             // it from a file.)
             node.Attributes("xmlns").Remove();
             // Inherit the parent namespace instead
             node.Name = node.Parent.Name.Namespace + node.Name.LocalName;
        }
        Console.WriteLine(doc); // Or doc.Save(...)
    }
}
票数 40
EN

Stack Overflow用户

发布于 2015-09-25 16:01:22

不需要‘删除’空的xmlns属性。添加空xmlns属性的全部原因是因为子节点的名称空间为空(= ''),因此与根节点不同。将相同的命名空间添加到您的孩子,也将解决这个“副作用”。

代码语言:javascript
复制
XNamespace xmlns = XNamespace.Get("http://my.namespace");

// wrong
var doc = new XElement(xmlns + "Root", new XElement("Firstelement"));

// gives:
<Root xmlns="http://my.namespace">
    <Firstelement xmlns="" />
</Root>

// right
var doc = new XElement(xmlns + "Root", new XElement(xmlns + "Firstelement"));

// gives:
<Root xmlns="http://my.namespace">
    <Firstelement />
</Root>
票数 21
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24305747

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档