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 中删除元素


- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01