Update XElement value in XDocument?

I have an XDocument with XElements, for example:

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

      

I want to find a Text element and update its value. I have LINQ, but it returns a value rather than allowing me to update the XElement and XDocument in response.

+2


source to share


1 answer


You cannot do this in a single LINQ statement - LINQ are queries and you are doing an update. You have to use LINQ to query the items you want to update, then go to the list in foreach

and apply the changes; eg:.



var pageContents = doc./* ... */.Elements("PageContents").Where(...);
foreach (var pageContent in pageContents)
{
    pageContent.Element("Text").Value = "Foo";
    pageContent.Element("Image").Value = "bar.jpg";
}

      

+7


source







All Articles