更新XDocument中的XElement值? [英] Update XElement value in XDocument?

查看:33
本文介绍了更新XDocument中的XElement值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有XElement的XDocument,例如:

I have a XDocument with XElements such as this:

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

我想找到Text元素并更新其值.我有一些LINQ在工作,但是它返回值,而不是允许我更新XElement和XDocument作为返回.

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.

推荐答案

您不能在单个LINQ语句中做到这一点-LINQ与查询有关,您正在进行更新.您应该使用LINQ来查询要更新的元素,然后遍历foreach中的列表并应用更改;否则,请使用LINQ.例如:

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

这篇关于更新XDocument中的XElement值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆