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

2 Answers 2

2

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.

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

Comments

1
        XDocument X_DOC = XDocument.Load(Application.StartupPath + "\\Sample.xml");
        X_DOC.Root.Elements("Child").Remove();
        X_DOC.Save(Application.StartupPath + "\\Sample.xml");

2 Comments

You should call Path.Combine. Also, you don't need the Where call.
@ SLaks : Thank you..... Edited in (line no. 2) .Kindly post an example for Path.Combile

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.