user3650845
user3650845

Reputation: 15

Edit the same attribute of multiples nodes inside xml file

I have a xml file like this:

<Atletas>
<Atleta Id="0" Nombre="Eduardo"/>
<Atleta Id="1" Nombre="Daniel" />
<Atleta Id="2" Nombre="Carlos" />
<Atleta Id="3" Nombre="Gabriel" />
<Atleta Id="4" Nombre="Pedro"/>
<Atleta Id="5" Nombre="Juan"/>
</Atletas>

After deleting some nodes using this query:

       XDocument doc = XDocument.Load(spath);
        try
        {
            var resultQuery = doc.Element("Atletas")
                   .Elements("Atleta")
                   .Where(x => (int?)x.Attribute("Id") == Convert.ToInt32(dGridTest.SelectedIndex.ToString()));

            if (resultQuery != null)
            {
                resultQuery.Remove();    
            }

            doc.Save(spath);

I have this result:

<Atletas>
<Atleta Id="0" Nombre="Eduardo"/>
<Atleta Id="1" Nombre="Daniel" />
<Atleta Id="4" Nombre="Pedro"/>
<Atleta Id="5" Nombre="Juan"/>
</Atletas>

The problem is, how can I edit the values of the Id=4 and Id=5 in order to have this xml:

<Atletas>
<Atleta Id="0" Nombre="Eduardo"/>
<Atleta Id="1" Nombre="Daniel" />
<Atleta Id="2" Nombre="Pedro"/>
<Atleta Id="3" Nombre="Juan"/>
</Atletas>

I'm using linq and wpf.

Upvotes: 0

Views: 45

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

You can get the attributes (after you remove the element), then use XAttribute.SetValue method

var attributes = doc.Element("Atletas")
                 .Elements("Atleta")
                 .Select(x => x.Attribute("Id"));

int i = 0;
foreach(var attr in attributes)
       attr.SetValue(i++);

doc.Save(spath);

Upvotes: 1

Related Questions