1

I'm trying to add a new attribute to an existing xml node, my xml looks like this:

<Atletas>
<Atleta Id="0" Nombre="TextBox4" Genero="Masculino" Edad="TextBox"  />
<Atleta Id="1" Nombre="TextBox345" Genero="Masculino" Edad="TextBox" />
<Atleta Id="2" Nombre="Daniel1" Genero="Masculino" Edad="TextBox"  />
<Atleta Id="3" Nombre="TextBox4" Genero="Masculino" Edad="TextBox" />
<Atleta Id="4" Nombre="Daniel2" Genero="Masculino" Edad="23" />
<Atleta Id="5" Nombre="Juan" Genero="Masculino" Edad="25" />
</Atletas>

I want my xml looks like this:

<Atletas>
<Atleta Id="0" Nombre="Daniel" Genero="Masculino" Edad="25" Peso="89" />
<Atleta Id="1" Nombre="John" Genero="Masculino" Edad="22"  />
<Atleta Id="2" Nombre="Tom" Genero="Masculino" Edad="21" Peso="78"/>
<Atleta Id="3" Nombre="Kerry" Genero="Masculino" Edad="18" />
<Atleta Id="4" Nombre="Peter" Genero="Masculino" Edad="23" Peso="76" />
<Atleta Id="5" Nombre="Juan" Genero="Masculino" Edad="25" />
</Atletas>

Using linq, how can i write a query in order to add a new attribute to a selected node using its Id as an identifier?

1 Answer 1

2

Use XElement.Add method to add content (like attributes) to elements:

var xdoc = XDocument.Load(path_to_xml);

var atleta = xdoc.Root.Elements("Atleta")
                 .FirstOrDefault(a => (int)a.Attribute("Id") == 3);

atleta.SetAttributeValue("Edad", 21);
atleta.Add(new XAttribute("Peso", 78));
xdoc.Save(path_to_xml);

After executing this code Atleta element with attribute Id equal to 3 will look like:

<Atleta Id="3" Nombre="TextBox4" Genero="Masculino" Edad="21" Peso="78"/>

Suggested reading: Programming Guide (LINQ to XML). If you have any questions to code above or other tasks you need to complete, then just read this guide.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.