How to delete nodes and subnodes using XDocument

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 637
I have xml as under
<databaseserver>
<server name="server1" serverid="1">
<databases>
<database dbid="1" dbname="db1" />
<database dbid="2" dbname="db2" />
</databases>
</server>
<server name="server2" serverid="2">
<databases>
<database dbid="1" dbname="db1" />
<database dbid="2" dbname="db2" />
</databases>
</server>
<server name="server3" serverid="3">
<databases>
<database dbid="1" dbname="db1" />
<database dbid="2" dbname="db2" />
</databases>
</server>
</databaseserver>

I want to delete the nodes and it's subnodes whose serverid="1".

Final output will be
<databaseserver>   
<server name="server2" serverid="2">
<databases>
<database dbid="1" dbname="db1" />
<database dbid="2" dbname="db2" />
</databases>
</server>
<server name="server3" serverid="3">
<databases>
<database dbid="1" dbname="db1" />
<database dbid="2" dbname="db2" />
</databases>
</server>
</databaseserver>


How can I do so?

Solution

static void Main(string[] args)
{
var input = @"<databaseserver>
<server name='server1' serverid='1'>
<databases>
<database dbid='1' dbname='db1' />
<database dbid='2' dbname='db2' />
</databases>
</server>
<server name='server2' serverid='2'>
<databases>
<database dbid='1' dbname='db1' />
<database dbid='2' dbname='db2' />
</databases>
</server>
<server name='server3' serverid='3'>
<databases>
<database dbid='1' dbname='db1' />
<database dbid='2' dbname='db2' />
</databases>
</server>
</databaseserver>";
var xDoc = XDocument.Parse(input);
xDoc.Descendants("server")
.First(s => s.Attribute("serverid").Value == "1")
.Remove();

var newXml = xDoc.ToString();

Console.ReadKey();
}

Comments or Responses

Login to post response