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 中删除元素
基础教程推荐
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
