使用 LINQ 从 xml 中删除元素 [英] delete element from xml using LINQ

查看:38
本文介绍了使用 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 中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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