0

I am trying to remove attributes from an xml whose value contains certain string.

This is the code I wrote,

XmlDocument doc = new XmlDocument();                                                          
doc.LoadXml("<book genre='#novel' ISBN='1-861001-57-5'>" +                                            
                "<title id ='#x'>Pride And Prejudice</title>" +
                "</book>");

   //Get the root element of the element
    XmlElement el = doc.DocumentElement;

    foreach (XmlElement a in doc.ChildNodes)
    {
        XmlAttributeCollection atributos = a.Attributes;

        foreach (XmlAttribute att in atributos)
        {
            if (att.Value.StartsWith("#"))
            {
                a.RemoveAttribute(att.Name); //Gives invalid operation exception
            }
        }
    }

In the second iteration, it gives me invalid operation error.

I looked around and found something that it could be because I am trying to modify the collection in the foreach loop.

If that is the case, what will be the best solution?

I generate an new xml?

jazb
  • 5,498
  • 6
  • 37
  • 44
Shad
  • 1,185
  • 1
  • 12
  • 27

1 Answers1

1

You can iterate through the attributes by index in reverse order, like the code below, and it will not throw the exception.

foreach (XmlElement a in doc.ChildNodes)
{
    XmlAttributeCollection atributos = a.Attributes;

    for (var i = atributos.Count - 1; i >= 0; i--)
    {
        var att = a.Attributes[i];
        if (att.Value.StartsWith("#"))
        {
            a.RemoveAttribute(att.Name);
        }
    }
}
Nathan Werry
  • 876
  • 7
  • 18