Adding removing xml attribute from XML File in .NET

SheoNarayan
Posted by in ASP.NET category on for Intermediate level | Views : 38495 red flag
Rating: 3 out of 5  
 1 vote(s)

While working with XML file, we sometimes need to add/ remove or even modify certain xml attributes, this article shows how to add/remove xml attributes from a XML file.

In order to show how to add/remove xml data attributes from the XML file, I have a sample xml file named "XMLFile1.xml" and has following contents.

<shape>

<rect x="2" y="3" style="fill:none;" width="87.857" height="12.143">

</rect>

<rect x="4" y="5.5" style="fill:red;" width="87.357" height="12.243">

</rect>

</shape>

 

Reading the XML File

Lets first see, how to read the xml file. You can use following function to do that. In below function I am getting the XmlReader by using XmlTextReader and passing the path of the file as parameter. Looping through each rect node and getting the attribute value.

 

C# Code

private void ReadXML()

{

StringBuilder strB = new StringBuilder("", 500);

XmlReader reader = new XmlTextReader(xmlFile);

try

{

while (reader.ReadToFollowing("rect"))

{

strB.Append("X: " + reader.GetAttribute("x").ToString());

strB.Append(" | Y: " + reader.GetAttribute("y").ToString());

strB.Append(" | style: " + reader.GetAttribute("style").ToString());

strB.Append("<hr />");

}

}

catch

{

throw;

}

finally

{

reader.Close();

}

Response.Write(strB.ToString());

}

VB.NET Code

Private Sub ReadXML()
    Dim strB As New StringBuilder("", 500)
    Dim reader As XmlReader = New XmlTextReader(xmlFile)
    Try
        While reader.ReadToFollowing("rect")
            strB.Append("z: " + reader.GetAttribute("z").ToString())
            strB.Append(" | Y: " + reader.GetAttribute("y").ToString())
            strB.Append(" | style: " + reader.GetAttribute("style").ToString())
            strB.Append("<hr />")
        End While
    Catch
        Throw
    Finally
        reader.Close()
    End Try
    Response.Write(strB.ToString())
End Sub
Get solutions of the .NET problems with video explanations, .pdf and source code in .NET How to's.
Adding and Removing XML Attributes

C# Code

private void AppendAttribute()

{

XmlDocument xmlDoc = new XmlDocument();

if (File.Exists(xmlFile))

{

xmlDoc.Load(xmlFile);

XmlNodeList list = xmlDoc.GetElementsByTagName("rect");

int i = 0;

foreach (XmlNode node in list)

{

i++;

// if element already there, it will override

XmlAttribute newAttr = xmlDoc.CreateAttribute("z");

newAttr.Value = i.ToString();

node.Attributes.Append(newAttr);

// Remove the y attribute

node.Attributes.RemoveNamedItem("y");

}

xmlDoc.Save(xmlFile);

}

}

VB.NET Code

Private Sub AppendAttribute()
    Dim xmlDoc As New XmlDocument()
    If File.Exists(xmlFile) Then
        xmlDoc.Load(xmlFile)
        Dim list As XmlNodeList = xmlDoc.GetElementsByTagName("rect")
        Dim i As Integer = 0
        For Each node As XmlNode In list
            System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
            ' if element already there, it will override
            Dim newAttr As XmlAttribute = xmlDoc.CreateAttribute("z")
            newAttr.Value = i.ToString()
            node.Attributes.Append(newAttr)

            ' remove xml attribute
            node.Attributes.RemoveNamedItem("x")
        Next

        xmlDoc.Save(xmlFile)
    End If
End Sub

To add a new attribute, first you can read the entire xml file using XmlDocument.Load method by passing filename as parameter. Then get all rect node collection by using GetElementByTagName method, loop through each node. Inside the loop, you can create a new XmlAttribute object with your desired attribute name (in this case I have used z). You can assign the value as well and then use node.Attributes.Append method by passing the XmlAttribute as parameter to add a new XmlAttribute called z.

Note that if you already have z attribute in your xml file then it will override its value.

To remove an attribute, you can use the node.Attributes.RemoveNamedItem and pass the name of the attribute you want to remove as parameter and the attribute will be removed.

Once you have done your addition and removal of attributes, ensure that you are saving your Xml document by using Save method of the XmlDocument.

The resultant xml file content after above operation will be like this.

<shape>

<rect y="3" style="fill:none;" width="87.857" height="12.143" z="1">

</rect>

<rect y="45" style="fill:red;" width="87.357" height="12.243" z="2">

</rect>

</shape>

Hope this quick article of manipulating xml attribute would be helpful. Thanks for reading. This article and one of my previous article will be further helpful to work with XML file.

To get subsequent articles alert in your email, please subscribe.

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)