Delete a node using XDocument

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 695
I have an xml as under

<databases>
<database dbid="1" dbserverid="1" dbname="db1" />
<database dbid="2" dbserverid="1" dbname="db2" />
<database dbid="3" dbserverid="2" dbname="db3" />
<database dbid="4" dbserverid="3" dbname="db4" />
</databases>

I want to delete the node whose dbserverid= "1". How to do so?

Solution

static void Main(string[] args)
{
var input = @"<databases>
<database dbid='1' dbserverid='1' dbname='db1' />
<database dbid='2' dbserverid='1' dbname='db2' />
<database dbid='3' dbserverid='2' dbname='db3' />
<database dbid='4' dbserverid='3' dbname='db4' />
</databases>";
var xDoc = XDocument.Parse(input);
xDoc.Descendants("database").Where(xa => xa.Attribute("dbserverid").Value == "1").Remove();

var newXml = xDoc.ToString();

Console.ReadKey();
}

Comments or Responses

Login to post response