Say I have a xml document that looks like this
<foo>
<bar id="9" />
<bar id="4" />
<bar id="3" />
</foo>
I would like to use linq to reset the id's to 0, 1 ,2. What would be the easiest way to do this?
Thanks
Say I have a xml document that looks like this
<foo>
<bar id="9" />
<bar id="4" />
<bar id="3" />
</foo>
I would like to use linq to reset the id's to 0, 1 ,2. What would be the easiest way to do this?
Thanks
XElement xml = GetXml();
var i = 0;
foreach (var e in xml.Elements("bar"))
e.SetAttributeValue("id", i++);
I was hoping for a nice 1 liner. Maybe that only exists in my linq dreams.
You can do it with linq methods instead of foreach, but there isn't much bang for the buck:
XElement xml = GetXml();
int updatedElements = xml.Elements("bar")
.Select((x, i) =>
{
x.SetAttributeValue("id", i);
return x;
})
.Count();
Here, the Count() method is necessary to enumerate the query. Anything that enumerates the query would do.
If using the Select as a mutator bothers you (as it does me), use List(T).ForEach instead:
XElement xml = GetXml();
xml.Elements("bar")
.Select( (x, i) => new {x, i})
.ToList()
.ForEach(a => a.x.SetAttributeValue("id", a.i));