3

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>  

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?

GilliVilla
  • 4,998
  • 11
  • 55
  • 96

2 Answers2

9

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

EDIT: 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();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    This works for all attributes except for - xmlns - in which case it still not getting removed. I am going topost that as a separate questions. – GilliVilla Aug 09 '11 at 22:44
  • @GilliVilla: Yes, `xmlns` is somewhat special in some ways, although I'd still expect it to work... I'll have a look at your new question tomorrow :) – Jon Skeet Aug 09 '11 at 22:45
1

if you have only these two attributes,

 doc.Element("A").Elements("B").Attributes().Remove();
Damith
  • 62,401
  • 13
  • 102
  • 153