简体   繁体   English

如何从 XDocument 中删除 xmlns 属性?

[英]How to remove xmlns attribute from XDocument?

In my C# codebase, I have an XDocument of the form:在我的 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>

Using Linq-to-XML or otherwise, I wanted to remove the xmlns for all the elements contained by element B.使用 Linq-to-XML 或其他方式,我想删除元素 B 包含的所有元素的xmlns

Using the methodology given here: How to Remove specific attributes in XMLDocument?使用此处给出的方法: 如何删除 XMLDocument 中的特定属性? , I was able to remove all attributes except xmlns ,我能够删除xmlns之外的所有属性

What is the best way to remove 'xmlns' attribute from XDocument ?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. 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. If you remove it from both places it's gone:如果你从这两个地方删除它,它就消失了:

doc.Descendants()
   .Attributes()
   .Where( x => x.IsNamespaceDeclaration )
   .Remove();

foreach (var elem in doc.Descendants())
    elem.Name = elem.Name.LocalName;

(The first part of the code above is copied from now deleted answer by Bertrand Marron.) (上面代码的第一部分是从 Bertrand Marron 现在删除的答案中复制的。)

If you wanted to remove namespaces from attributes too, that's little more complicated, because their Name is read-only:如果您也想从属性中删除命名空间,那会稍微复杂一些,因为它们的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM