Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Remove specific attributes in 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>  

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?

like image 777
GilliVilla Avatar asked Mar 02 '26 09:03

GilliVilla


2 Answers

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();
like image 149
Jon Skeet Avatar answered Mar 04 '26 22:03

Jon Skeet


if you have only these two attributes,

 doc.Element("A").Elements("B").Attributes().Remove();
like image 41
Damith Avatar answered Mar 04 '26 22:03

Damith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!