How to Remove specific attributes in XMLDocument?

2019-05-27 07:47发布

问题:

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?

回答1:

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


回答2:

if you have only these two attributes,

 doc.Element("A").Elements("B").Attributes().Remove();