如何从XDocument删除xmlns属性? [英] How to remove xmlns attribute from XDocument?

查看:110
本文介绍了如何从XDocument删除xmlns属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#代码库中,我有一个XDocument格式:

In my C# codebase, I have an XDocument of the form:

<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.

Using Linq-to-XML or otherwise, I wanted to remove the xmlns for all the elements contained by element B.

使用此处提供的方法:如何删除XMLDocument中的特定属性?,我能够删除所有属性,除了 xmlns

Using the methodology given here: How to Remove specific attributes in XMLDocument?, I was able to remove all attributes except xmlns

XDocument中删除'xmlns'属性的最佳方法是什么?

What is the best way to remove 'xmlns' attribute from XDocument?

推荐答案

似乎名称空间信息保存在对象树中的两个位置,该对象树表示LINQ to XML中的XML文档:作为实际的xmlns属性,并且元素的Name.如果您从两个地方都将其删除,那么它就消失了:

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' Names. 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;

(上面代码的第一部分是Bertrand Marron从现在删除的答案中复制的.)

(The first part of the code above is copied from now deleted answer by Bertrand Marron.)

如果您也想从属性中删除名称空间,则稍微复杂一点,因为它们的Name是只读的:

If you wanted to remove namespaces from attributes too, that's little more complicated, because their Name is read-only:

foreach (var attr in doc.Descendants().Attributes())
{
    var elem = attr.Parent;
    attr.Remove();
    elem.Add(new XAttribute(attr.Name.LocalName, attr.Value));
}

这篇关于如何从XDocument删除xmlns属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆