Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove attribute if it exists from xmldocument

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".

like image 653
nav100 Avatar asked Jul 08 '11 19:07

nav100


2 Answers

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>
like image 79
Grant Winney Avatar answered Nov 20 '22 07:11

Grant Winney


youcan use XmlNamedNodeMap.RemoveNamedItem Method (name) to do it. It can be used to Attributes.It will return the XmlNode removed from this XmlNamedNodeMap or a null reference (Nothing in Visual Basic) if a matching node was not found.

    [C#] 
    using System;
    using System.IO;
    using System.Xml;

   public class Sample
   {
    public static void Main()
    {
     XmlDocument doc = new XmlDocument();
     doc.LoadXml("<book genre='novel' publicationdate='1997'> " +
                 "  <title>Pride And Prejudice</title>" +
                 "</book>");      

     XmlAttributeCollection attrColl = doc.DocumentElement.Attributes;

     // Remove the publicationdate attribute.
     attrColl.RemoveNamedItem("publicationdate");

     Console.WriteLine("Display the modified XML...");
     Console.WriteLine(doc.OuterXml);

     }
   }
like image 1
legendJSLC Avatar answered Nov 20 '22 07:11

legendJSLC