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

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

问题描述

在我的C#代码库,我有如下形式的的XMLDocument:



<预类=郎咸平的XML prettyprint-覆盖> < A> ;
< B>
c为C的xmlns =布拉布拉YZ ='blablaaa'>喜< / C>
< d的xmlns =布拉布拉YZ ='blablaaa'>如何< / D>
<,E的xmlns =布拉布拉YZ ='blablaaa'>是< / E>
<˚F的xmlns =布拉布拉YZ ='blablaaa'> YOU< / F>
< / B>
< B>
c为C的xmlns =布拉布拉YZ ='blablaaa'> I< / C>
< d的xmlns =布拉布拉YZ ='blablaaa'> AM< / D>
<,E的xmlns =布拉布拉YZ ='blablaaa'>精< / E>
<˚F的xmlns =布拉布拉YZ ='blablaaa'>感谢< / F>
< / B>





使用LINQ到XML或以其他方式,我想删除的xmlns 为所有元素b包含的元素。



使用方法给出在这里:如何在为XMLDocument删除特定的属性,我能删除所有属性除了 的xmlns



什么是去除'的xmlns的最佳方式从为XMLDocument'属性?


解决方案

这似乎命名空间的信息都保存在一个表示LINQ to XML中的XML文档对象树两个地方:如实际的xmlns 属性和元素内部名称秒。

  doc.Descendants()
.Attributes()$ B $:如果您从两个地方就不见了删除b。凡(X => x.IsNamespaceDeclaration)
卸下摆臂();

的foreach(在doc.Descendants VAR ELEM())
elem.Name = elem.Name.LocalName;



(上面的代码是由贝特朗·马龙现在删除了答案复制的第一部分。)



如果你想删除的属性也命名空间,这是有点复杂,因为他们的名称是只读的:

 的foreach(在doc.Descendants VAR ATTR()。属性())
{
VAR ELEM = attr.Parent;
attr.Remove();
elem.Add(新XAttribute(attr.Name.LocalName,attr.Value));
}


In my C# codebase, I have a XMLDocument 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>

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

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

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

解决方案

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;

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

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));
}

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

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