How to Remove specific attributes in XMLDocument?

可紊 提交于 2019-12-06 09:47:19

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

if you have only these two attributes,

 doc.Element("A").Elements("B").Attributes().Remove();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!