Search code examples
c#xmlc#-4.0xelement

How To remove a specific tag from XElement


Please consider this XML:

<Employees>
    <Person>
        <ID>1000</ID>
        <Name>Nima</Name>
        <LName>Agha</LName>
    </Person>
    <Person>
        <ID>1002</ID>
        <Name>Ligha</Name>
        <LName>Ligha</LName>
    </Person>
    <Person>
        <ID>1003</ID>
        <Name>Jigha</Name>
        <LName>Jigha</LName>
    </Person>
</Employees>

I load it in to a Xelement variable.Now How I can remove second Person tag from above XML?

thanks


Solution

  • If the only condition is the second node Person, you can use this.

    XElement  rootElement = .... // init your rootElement as you want 
    
    rootElement.Elements("Person").Skip(1).Remove() ;