views:

468

answers:

3

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

+3  A: 
XElement xml = GetXml();
var i = 0;
foreach (var e in xml.Elements("bar"))
  e.SetAttributeValue("id", i++);
Will
A: 

I was hoping for a nice 1 liner. Maybe that only exists in my linq dreams.

Ryan
A: 

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));
David B
In most case, we can get more simple code than statement with query. But it seems not in this case.
Sonic Lee
Sure, Functional programming techniques are not so great at generating side-effects.
David B