LINQ to XML Question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • stoogots2
    New Member
    • Sep 2007
    • 77

    LINQ to XML Question

    I have the following XML structure from which I want to select/remove the "second" Element which has the Attribute "Name" whose value = "Test"
    Code:
    <Application>
    <first>
    <second Name="Test">
    </second>
    <second Name="Whatever">
    </second>
    </first>
    </Application>
    
    var x = from c in xd.Element("Application").Element("first").Descendants()
               where c.Element("Application").Element("first").Element("second").Attribute("Name").Value=="Test"
    select c;
    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.
  • stoogots2
    New Member
    • Sep 2007
    • 77

    #2
    Resolved

    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.

    Code:
    XDocument xd = XDocument.Load(sXmlFile);
                    var x = from c in xd.Descendants("second")
                            where c.Attribute("Name").Value == "Test"
                            select c;
    
    // To remove all matching elements
    x.Remove();
    
    // To Save after finished
    xd.Save(sXmlFile);

    Comment

    Working...