tags:

views:

46

answers:

2

I've an xml file (Sample.xml) which has the following structure

    <RootElement>     
        <Child Name="FirstChild" Start="1" End="2"/>
        <Child Name="SecondChild" Start="0" End="2"/>           
        <Child Name="ThirdChild" Start="1" End="2"/>            
        <Child Name="FourthChild" Start="0" End="2"/>            
        <Child Name="FifthChild" Start="0" End="2"/>            
        <Child Name="SixthChild" Start="1" End="2"/>   
        <MatchedChilds>  
            <Child Name="FirstChild" />  
            <Child Name="SecondChild" />  
            <Child Name="ThirdChild" />  
            <Child Name="FourthChild" />  
            <Child Name="FifthChild" />  
            <Child Name="SixthChild" />   
    </MatchedChilds> 
</RootElement> 

i need to remove the elements "Child" if it is directly under "RootElement"

please give me a XML to LINQ approch to do this

+1  A: 

You need to loop over the nodes and remove them, like this:

foreach(var child in root.Elements("Child").ToArray())
    child.Remove();

The Elements call will return all direct child elements of the element you call it on; it will not return grandchildren;

You must call ToArray or you'll be modifying the collection as you enumerate it.

SLaks
+1  A: 
        XDocument X_DOC = XDocument.Load(Application.StartupPath + "\\Sample.xml");
        X_DOC.Root.Elements("Child").Remove();
        X_DOC.Save(Application.StartupPath + "\\Sample.xml");
Pramodh
You should call `Path.Combine`. Also, you don't need the `Where` call.
SLaks
@ SLaks : Kindly post a sample code
Pramodh
@ SLaks : Thank you..... Edited in (line no. 2) .Kindly post an example for Path.Combile
Pramodh