問題描述
我有一個 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 中刪除元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!