Connecting Tech Pros Worldwide Help | Site Map

LINQ to XML Question

Member
 
Join Date: Sep 2007
Posts: 70
#1: Oct 14 '09
I have the following XML structure from which I want to select/remove the "second" Element which has the Attribute "Name" whose value = "Test"
Expand|Select|Wrap|Line Numbers
  1. <Application>
  2. <first>
  3. <second Name="Test">
  4. </second>
  5. <second Name="Whatever">
  6. </second>
  7. </first>
  8. </Application>
  9.  
  10. var x = from c in xd.Element("Application").Element("first").Descendants()
  11.            where c.Element("Application").Element("first").Element("second").Attribute("Name").Value=="Test"
  12. select c;
  13.  
Anyway what I have above does not work, and I've tried a lot of different things to no avail. There is something important that I seem to be missing about LINQ to XML. I read that I should be able to use Descendants() anywhere (without having to specify the hierarchy in element.element type syntax), but I haven't gotten that to work with a where clause or condition.
Member
 
Join Date: Sep 2007
Posts: 70
#2: Oct 15 '09

re: LINQ to XML Question


Resolved. Not sure why this didn't work the first time...

Here is the code to find the matching elements / remove them / and save the xml file.

Expand|Select|Wrap|Line Numbers
  1. XDocument xd = XDocument.Load(sXmlFile);
  2.                 var x = from c in xd.Descendants("second")
  3.                         where c.Attribute("Name").Value == "Test"
  4.                         select c;
  5.  
  6. // To remove all matching elements
  7. x.Remove();
  8.  
  9. // To Save after finished
  10. xd.Save(sXmlFile);
  11.  
  12.  
Reply