views:

844

answers:

1

I have a XDocument with XElements such as this:

<PageContent>
  <Text>My Text</Text>
  <Image>image.jpg</Image>
</PageContent>

I want to find the Text element and update its value. I have some LINQ working but its returning the value rather than allowing me to update the XElement and XDocument in return.

+3  A: 

You can't do it in a single LINQ statement - LINQ is about queries, and you're doing an update. You should use LINQ to query for elements you want to update, and then go through the list in foreach and apply the changes; e.g.:

var pageContents = doc./* ... */.Elements("PageContents").Where(...);
foreach (var pageContent in pageContents)
{
    pageContent.Element("Text").Value = "Foo";
    pageContent.Element("Image").Value = "bar.jpg";
}
Pavel Minaev
I have done this:var q = XMLData.Descendants("PageContent").Descendants().SingleOrDefault(x => x.Name == item.Key); q.Value = item.Value;However when I look at XMLData nothing has changed
Jon
Your query sounds fine. If you aren't seeing the change, then it is most likely because of the way you're checking for it. Can you post the code that you use to verify that the change had happened?
Pavel Minaev