![](/img/trans.png)
[英]How to remove xmlns attribute of a node other than root in an XDocument?
[英]How to remove xmlns attribute from XDocument?
在我的 C# 代碼庫中,我有一個形式為XDocument
:
<A>
<B>
<C xmlns='blabla' yz='blablaaa'> Hi </C>
<D xmlns='blabla' yz='blablaaa'> How </D>
<E xmlns='blabla' yz='blablaaa'> Are </E>
<F xmlns='blabla' yz='blablaaa'> You </F>
</B>
<B>
<C xmlns='blabla' yz='blablaaa'> I </C>
<D xmlns='blabla' yz='blablaaa'> am</D>
<E xmlns='blabla' yz='blablaaa'> fine</E>
<F xmlns='blabla' yz='blablaaa'> thanks</F>
</B>
使用 Linq-to-XML 或其他方式,我想刪除元素 B 包含的所有元素的xmlns
。
使用此處給出的方法: 如何刪除 XMLDocument 中的特定屬性? ,我能夠刪除除xmlns
之外的所有屬性
從XDocument
中刪除 'xmlns' 屬性的最佳方法是什么?
It seems the namespace information are kept in two places in the object tree that represents the XML document in LINQ to XML: as actual xmlns
attributes and inside the elements' Name
s. 如果你從這兩個地方刪除它,它就消失了:
doc.Descendants()
.Attributes()
.Where( x => x.IsNamespaceDeclaration )
.Remove();
foreach (var elem in doc.Descendants())
elem.Name = elem.Name.LocalName;
(上面代碼的第一部分是從 Bertrand Marron 現在刪除的答案中復制的。)
如果您也想從屬性中刪除命名空間,那會稍微復雜一些,因為它們的Name
是只讀的:
foreach (var attr in doc.Descendants().Attributes())
{
var elem = attr.Parent;
attr.Remove();
elem.Add(new XAttribute(attr.Name.LocalName, attr.Value));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.