remove attribute if it exists from xmldocument

nav100 picture nav100 · Jul 8, 2011 · Viewed 25.3k times · Source

How to remove the attribute from XmlDocument if attribute exists in the document? Please help. I am using RemoveAttribute but how can I check if it exists.

root.RemoveAttribute(fieldName);

Thanks..

 <?xml version="1.0" standalone="yes" ?> 
 <Record1>
  <Attribute1 Name="DataFieldName" Value="Pages" /> 
 </Record1> 

I am trying to remove attribute named "DataFieldName".

Answer

Grant Winney picture Grant Winney · Jul 8, 2011

Not sure exactly what you're trying to do, so here's two examples.

Removing the attribute:

var doc = new System.Xml.XmlDocument();
doc.Load("somefile.xml");
var root = doc.FirstChild;

foreach (System.Xml.XmlNode child in root.ChildNodes)
{
    if (child.Attributes["Name"] != null)
        child.Attributes.Remove(child.Attributes["Name"]);
}

Setting the attribute to an empty string:

var doc = new System.Xml.XmlDocument();
doc.Load("somefile.xml");
var root = doc.FirstChild;

foreach (System.Xml.XmlNode child in root.ChildNodes)
{
    if (child.Attributes["Name"] != null)
        child.Attributes["Name"].Value = "";
}

Edit: I can try to modify my code if you elaborate on your original request. An XML document can only have one root node and yours appears to be record1. So does that mean your entire file will only contain a single record? Or did you mean to have something like

<?xml version="1.0" standalone="yes" ?>
<Records>
    <Record>
        <Attribute Name="DataFieldName" Value="Pages" />
    </Record>
    <Record>
        <Attribute Name="DataFieldName" Value="Pages" />
    </Record>
</Records>