Update XElement value in XDocument?

时间秒杀一切 提交于 2019-12-13 14:49:08

问题


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.


回答1:


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";
}


来源:https://stackoverflow.com/questions/1336983/update-xelement-value-in-xdocument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!