Mohamed Ben Dhaou
Mohamed Ben Dhaou

Reputation: 1124

How to add new counter attribute to xml nodes with C#

I am looking how to add a new attribute count to xml nodes to have it as an id for further parsing.

My XML:

<objects>
    <object name="Ford Fuigo" type="Car">
          <properties>
           ...      
           </properties>
    </object>
    <object name="Renault Clio" type="Car">
          <properties>
           ...      
           </properties>
    </object>
    <object name="Evico Star" type="Bus">
          <properties>
           ...      
           </properties>
    </object>
</objects>

And I want to have a new attribute like this:

<objects>
    <object count ="1" name="Ford Fuigo" type="Car">
          <properties>
           ...      
           </properties>
    </object>
    <object count ="2" name="Renault Clio" type="Car">
          <properties>
           ...      
           </properties>
    </object>
    <object count ="3" name="Evico Star" type="Bus">
          <properties>
           ...      
           </properties>
    </object>
</objects>

Upvotes: 1

Views: 140

Answers (1)

Andrew
Andrew

Reputation: 3796

Create XmlDocument based on your XML and then use SelectSingleNode to find nodes and change them

http://msdn.microsoft.com/en-us/library/fb63z0tw.aspx

you can also use XElement like following:

XElement root = XElement.Load("input.xml");
int counter = 0;
foreach (var obj in root.Descendants("object"))
{
    obj.Add(new XAttribute("count", ++counter));
}

root.Save("output.xml");

Upvotes: 2

Related Questions