Remove attribute from XmlNode

how to remove an attribute from a System.Xml.XmlNode object in C #. The code I tried does not work. It throws an exception "the node to be deleted is invalid child node"

foreach (XmlNode distribution 
         in responseXml.SelectNodes("/Distributions/Distribution/DistributionID"))
{
  XmlAttribute attribute = null;
  foreach (XmlAttribute attri in distribution.Attributes)
  {
    if (attri.Name == "GrossRevenue")
      attribute = attri;
  }
  if (attribute != null) 
    distribution.ParentNode.RemoveChild(attribute);
}
+5
source share
1 answer

XmlAttributes is not XmlNodes. XmlNode.ChildNodeshas a type XmlNodeList, but XmlNode.Attributeshas a type XmlAttributesCollection. To remove an attribute, you use the XmlAttributesCollection.Removeor method .RemoveAt. In your code:

distribution.ParentNode.Attributes.Remove(attribute); 
+8
source

All Articles