[英]How to remove xmlns attribute of a node other than root in an XDocument?
我正在使用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
屬性。 我試過使用從這個問題的答案中得到啟發的代碼:
inner = new XElement(inner.Name.LocalName, inner.Elements());
調試時, xmlns
屬性從中消失了,但是我遇到了同樣的異常。
我認為下面的代碼是您想要的。 您需要將每個元素放入正確的名稱空間, 並刪除受影響元素的所有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(...)
}
}
無需“刪除”空的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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.