Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an attribute from XmlNode

Tags:

c#

xml

how to remove an attribute from an System.Xml.XmlNode object in C#. The Code I tried did not work. It throw an exception "node to be removed is not valid 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);
}
like image 589
Amzath Avatar asked Dec 29 '11 20:12

Amzath


People also ask

How to Remove an attribute from Xml node?

The removeChild() method removes a specified node. The removeAttribute() method removes a specified attribute.


1 Answers

XmlAttributes are not XmlNodes. XmlNode.ChildNodes is of type XmlNodeList, while XmlNode.Attributes is of type XmlAttributesCollection. To remove an attribute, you use the XmlAttributesCollection.Remove or .RemoveAt method. In your code:

distribution.ParentNode.Attributes.Remove(attribute); 
like image 148
Joshua Honig Avatar answered Oct 27 '22 00:10

Joshua Honig