如何删除的XMLDocument特定属性? [英] How to Remove specific attributes in XMLDocument?

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

问题描述

在我的C#代码库,我有一个的XMLDocument 的形式为:

In my C# codebase, I have a XMLDocument of the form:

<A>
<B>
<C mlns='blabla' yz='blablaaa'> Hi </C>
<D mlns='blabla' yz='blablaaa'> How </D>
<E mlns='blabla' yz='blablaaa'> Are </E>
<F mlns='blabla' yz='blablaaa'> You </F>
</B>
<B>
<C mlns='blabla' yz='blablaaa'> I </C>
<D mlns='blabla' yz='blablaaa'> am</D>
<E mlns='blabla' yz='blablaaa'> fine</E>
<F mlns='blabla' yz='blablaaa'> thanks</F>
</B>
</A>  



使用LINQ到XML或以其他方式,我想删除 mlns YZ 属性所有元素包含的元素 B

Using Linq-to-XML or otherwise, I want to remove the mlns and yz attributes for all the elements contained by element B.

什么是实现这一目标的最佳途径?

What is the best way to achieve it?

推荐答案

使用LINQ to XML ..

Using LINQ to XML...

public static void RemoveAttributes(XNode parent, XName attribute)
{
    // I'm not sure what would happen if we tried to remove the attribute
    // while querying... seems like a bad idea.
    var list = parent.Descendants()
                     .Attributes(attribute)
                     .ToList();

    foreach (var attribute in list)
    {
        attribute.Remove();
    }
}



然后:

Then:

RemoveAttributes(doc, "mlns");
RemoveAttributes(doc, "yz");



编辑:我刚刚注意到,它应该是更容易,事实上,使用 删除 扩展方法:

I've just noticed that it should be even easier, in fact, using the Remove extension method:

public static void RemoveAttributes(XNode parent, XName attribute)
{
    parent.Descendants()
          .Attributes(attribute)
          .Remove();

}



所以,你甚至可以做到这一点没有方法很简单:

So you could even do it without the method pretty simply:

doc.Descendants().Attributes("mlns").Remove();
doc.Descendants().Attributes("yz").Remove();

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

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