6

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.

Here is my code :

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?

1 Answer 1

13

EDIT: 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.

Sign up to request clarification or add additional context in comments.

6 Comments

deleteQuery is returing an empty list when it is not given the first element's value in textbox
@Shishir: See my edit. While your code is using completely different names from your sample XML, and you haven't explained what you really want to happen, it's very hard to help you.
@Shishir: It's somewhat better now, but you haven't shown a domain element to remove. You're making it very hard to help you.
thanks a lot ...I've updated my question. it will be qry.Element("site").Remove()
@Shishir: Having edited your question (you should really look at the preview) it's getting a bit clearer... although you haven't helped yourself by being so vague.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.