-2

Here is my xml

 <result>
  <client></client>
  <message></message>
  <record>
     <message></message>
   </record>
</result>

I want to remove the "message" node which is right below "result" when I tried to remove it by using below code:

 responseXml.Descendants().Where(e => e.Name == "client" || e.Name == "message").Remove();

It is removing "message" which is under "record" but I don't want this. I want to remove only "message" under "result"

Expected xml:

 <result>
  <client></client>
  <record>
     <message></message>
   </record>
</result>

Please suggest me here.

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
user1893874
  • 823
  • 4
  • 15
  • 38
  • 1
    Why is `` still in your expected xml? – Eser Sep 11 '15 at 18:41
  • Consider checking out behavior of methods you are using - sometimes you may find answer yourself. For this - http://stackoverflow.com/questions/3705020/what-is-the-difference-between-linq-to-xml-descendants-and-elements – Alexei Levenkov Sep 11 '15 at 18:59

3 Answers3

5

Descendants() will return all elements (children and grand-children etc.), while Elements() will only return immediate children.

responseXml.Root.Elements().Where(e => e.Name == "message").Remove();

You could probably use the shorter .Element("message") syntax, but be aware that this method only returns the first element found. If you have more than one <message> it wont return/remove them all.

Christoffer Lette
  • 14,346
  • 7
  • 50
  • 58
1
void Main()
{
    string xml =@"
 <result>
  <client></client>
  <message></message>
  <record>
     <message></message>
   </record>
</result>";

XElement root = XElement.Parse(xml);    
root.Element("message").Remove();    
}

Removes exact element "message" directly under root node.

monkeyjumps
  • 702
  • 1
  • 14
  • 24
1

You can call Element(name), which returns a single XElement (calling Elements or Descendants returns a IEnumerable<XElement>):

responseXml.Root.Element("message").Remove();
w.b
  • 11,026
  • 5
  • 30
  • 49