使用LINQ的XML元素删除 [英] delete element from xml using LINQ

查看:128
本文介绍了使用LINQ的XML元素删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我已经像一个XML文件:

Hello 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>

现在我需要删除任何<网站> ...< /站点> 和值会随机从一个文本框定

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

如果我把第一个元素的值在文本框中,然后就可以删除它,但如果我把除了第一个元素的值元素的任何值,它可能无法删除!我需要我会把任何元素......任何价值,因为它可以第二元素或第三或第四等等....谁能帮我吗? !感谢先进

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? thanks in advanced!

推荐答案

编辑:好的,有进一步的编辑,它更清晰,你想要做什么,因为它发生很比你让,感谢 删除显著容易>的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();



这就是你所需要的。

That's all you need.

这篇关于使用LINQ的XML元素删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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