如何删除非超级节点的xmlns属性在一个XDocument [英] How to remove xmlns attribute of a node other than root in an XDocument
问题描述
我用的XDocument
,试图在第一个删除的xmlns =
属性内节点:
I'm using XDocument
to try and remove an xmlns=""
attribute on the first inner node:
<Root xmlns="http://my.namespace">
<Firstelement xmlns="">
<RestOfTheDocument />
</Firstelement>
</Root>
所以,我想作为一个结果是:
So what I want as a result is:
<Root xmlns="http://my.namespace">
<Firstelement>
<RestOfTheDocument />
</Firstelement>
</Root>
code
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
问题
当试图保存文档时,我得到了以下异常:
Problem
Upon trying to save the document, I get the following exception:
在preFIX'''不能从重新定义'到' HTTP://my.namespace 相同的开始元素标记内
The prefix '' cannot be redefined from '' to 'http://my.namespace' within the same start element tag.
这是什么意思,甚至我能做些什么来消除讨厌的的xmlns =
?
What does this even mean and what can I do to remove that pesky xmlns=""
?
- 我也想保持根节点的命名空间
- 我只想要那个特定的
的xmlns
删除,不会再有其他的的xmlns
属性在文档中。
- I do want to keep the root node's namespace
- I only want that specific
xmlns
removed, there will be no otherxmlns
attributes in the document.
我用code的答案灵感在这个问题尝试:
I've tried using code inspired from answers on this question:
inner = new XElement(inner.Name.LocalName, inner.Elements());
在调试时,的xmlns
属性已经从它,但我得到了同样的异常。
When debugging, the xmlns
attribute is gone from it but I get the same exception.
推荐答案
我觉得下面的code是你想要的。你需要把每一个元素到合适的命名空间,和的删除任何的xmlns =''
属性受影响的元素。后一部分是必需的,否则的LINQ to XML基本上试图离开你的元素
I think the code below is what you want. You need to put each element into the right namespace, and remove any xmlns=''
attributes for the affected elements. The latter part is required as otherwise LINQ to XML basically tries to leave you with an element of
<!-- This would be invalid -->
<Firstelement xmlns="" xmlns="http://my.namespace">
这里的code:
Here's the code:
using System;
using System.Xml.Linq;
class Test
{
static void Main()
{
XDocument doc = XDocument.Load("test.xml");
foreach (var node in doc.Root.Descendants())
{
// If we have an empty namespace...
if (node.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属性在一个XDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!