Reputation: 153
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
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