delete element from xml using LINQ(使用 LINQ 从 xml 中删除元素)
问题描述
我有一个 xml 文件,例如:
I've a xml file like:
<starting>
<start>
<site>mushfiq.com</site>
<site>mee.con</site>
<site>ttttt.co</site>
<site>jkjhkhjkh</site>
<site>jhkhjkjhkhjkhjkjhkh</site>
<site>dasdasdasdasdasdas</site>
</start>
</starting>
现在我需要删除任何 <site>...</site>
并且值将从文本框中随机给出.
Now I need to delete any <site>...</site>
and value will randomly be given from a textbox.
这是我的代码:
XDocument doc = XDocument.Load(@"AddedSites.xml");
var deleteQuery = from r in doc.Descendants("start") where r.Element("site").Value == txt.Text.Trim() select r;
foreach (var qry in deleteQuery)
{
qry.Element("site").Remove();
}
doc.Save(@"AddedSites.xml");
如果我把第一个元素的值放在文本框中,那么它可以删除它,但是如果我把除了第一个元素的值之外的任何元素值都不能删除!我需要输入任何元素的任何值...因为它可以是第 2 个元素或第 3 个或第 4 个等等....任何人都可以帮助我吗?
If I put the value of first element in the textbox then it can delete it, but if I put any value of element except the first element's value it could not able to delete! I need I'll put any value of any element...as it can be 2nd element or 3rd or 4th and so on.... can anyone help me out?
推荐答案
好的,通过进一步的编辑,你想做什么就更清楚了,而且碰巧它比你做的要容易得多,这要归功于Remove
扩展方法 在 IEnumerable<T>其中 T : XNode
:
Okay, with further editing, it's clearer what you want to do, and as it happens it's significantly easier than you're making it, thanks to the Remove
extension method on IEnumerable<T> where T : XNode
:
string target = txt.Text.Trim();
doc.Descendants("start")
.Elements("site")
.Where(x => x.Value == target)
.Remove();
这就是你所需要的.
这篇关于使用 LINQ 从 xml 中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 LINQ 从 xml 中删除元素


基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01