JonHiggens
JonHiggens

Reputation: 153

using linq, update one node in an xml item

Is there an easy way to update one node of an xml item? I have this:

 <userlist>
  <users>
    <name>bob</name>
    <userid>1</userid>
  </users>
  <users>
   ...etc...

I need to update the name in userid #1. I have this (hardcoded for clarity, not how it'll function):

XDocument userDoc = XDocument.Load(path);

var userList = from users in userDoc.Descendants("userlist")
                  where users.Element("userid").Value == "1"
                  select users;

foreach (XElement user in userList)
{
  user.SetElementValue("name", "Phil");
}

Is there a better way to do this? Thanks!

Upvotes: 2

Views: 180

Answers (1)

parapura rajkumar
parapura rajkumar

Reputation: 24413

You can use First

        var firstUser = (from users in userDoc.Descendants("userlist")
                       where users.Element("userid").Value == "1"
                       select users).First();

        firstUser.SetElementValue("name", "Phil");

or

userDoc.Descendants("userlist").First( x => x.Element("userid").Value == "1" ).SetElementValue( "name", "Phil");

Upvotes: 1

Related Questions