如何在XDocument中删除除root之外的节点的xmlns属性

情况

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

      

所以我想要的结果是:

      

 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 

问题

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

在同一个start元素标记内,前缀”不能从”重新定义为’ http://my.namespace ‘。

这甚至意味着什么,我该怎么做才能删除那个讨厌的xmlns=""

笔记

  • 我确实想保留根节点的命名空间
  • 我只想删除特定的xmlns ,文档中不会有其他xmlns属性。

更新

我尝试过使用这个问题的答案启发的代码:

 inner = new XElement(inner.Name.LocalName, inner.Elements()); 

调试时, xmlns属性已从中消失,但我得到了相同的exception。

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

   

这是代码:

 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(...) } } 

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

 XNamespace xmlns = XNamespace.Get("http://my.namespace"); // wrong var doc = new XElement(xmlns + "Root", new XElement("Firstelement")); // gives:    // right var doc = new XElement(xmlns + "Root", new XElement(xmlns + "Firstelement")); // gives: