Go to DotNetFunda.com
 Online : 1257 |  Welcome, Guest!   Login
 
Home > Articles > ASP.NET > Adding removing xml attribute from XML File in .NET
  • Nominate yourself for FREE online training by Microsoft MVP on OOPS, ASP.NET, ADO.NET and Sql Server.
    Brought to you by DotNetFunda.Com. You can refer to your friends as well !

  • Now you can recommend your article from any website to be selected as "Article of the Day" on DotNetFunda.Com website. If approved, that article will be featured on our home page.

General Notice: If you found copied contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.

Submit Article | Articles Home | Search Articles |

Adding removing xml attribute from XML File in .NET

 Posted on: 6/21/2009 12:55:43 AM by SheoNarayan | Views: 1872 | Category: ASP.NET | Level: Intermediate | Print Article
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.

Ask all your .NET related questions/clarifications here to get quicker solution.

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


Interesting?   Share and Bookmark this kick it on DotNetKicks.com


About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:Starter
Status: [Administrator]
Biography:Throughout 1st in all educational exams.
Major qualifications: HDCS, ADCA, MCA, MCTS
Location: Hyderabad, India
 Latest post(s) from SheoNarayan

   ◘ Common operation with Files and Folders in ASP.NET posted on 9/4/2009 4:23:03 PM
   ◘ Working with CustomValidator control in ASP.NET posted on 8/19/2009 9:27:43 AM
   ◘ Backup and Restore database in ASP.NET posted on 8/7/2009 5:30:24 PM
   ◘ Passing data between layers using Generic list collection posted on 7/19/2009 7:28:40 AM
   ◘ jQuery and ASP.NET AJAX UpdatePanel posted on 7/17/2009 6:53:04 PM


Submit Article


About Us | The Team | Advertise | Contact Us | Feedback | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
All rights reserved to DotNetFunda.Com. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
(Best viewed in IE 6.0+ or Firefox 2.0+ at 1024 * 768 or higher)