情况
我正在使用XDocument
尝试删除第一个内部节点上的xmlns=""
属性:
<Root xmlns="http://my.namespace">
<Firstelement xmlns="">
<RestOfTheDocument />
</Firstelement>
</Root>
因此,我想要的结果是:
<Root xmlns="http://my.namespace">
<Firstelement>
<RestOfTheDocument />
</Firstelement>
</Root>
代码
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=""
呢?
备注
xmlns
,则文档中将不会有其他xmlns
属性。更新
我曾尝试使用受this question答案启发的代码
inner = new XElement(inner.Name.LocalName, inner.Elements());
在调试时,xmlns
属性从其中消失了,但我得到了相同的异常。
发布于 2014-06-19 22:37:10
我认为下面的代码就是你想要的。您需要将每个元素放入正确的名称空间,并删除受影响元素的所有xmlns=''
属性。后面的部分是必需的,否则LINQ to XML基本上会给您留下一个
<!-- This would be invalid -->
<Firstelement xmlns="" xmlns="http://my.namespace">
代码如下:
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(...)
}
}
发布于 2015-09-25 16:01:22
不需要‘删除’空的xmlns属性。添加空xmlns属性的全部原因是因为子节点的名称空间为空(= ''),因此与根节点不同。将相同的命名空间添加到您的孩子,也将解决这个“副作用”。
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>
https://stackoverflow.com/questions/24305747
复制相似问题