markknowsley
Programmer
Using the following XML file as an example:
I want to write a C# method that will delete the Book node with the Id='2'.
I have the following code:
which removes the first node with the id 'Book'. Please can someone tell me how i can modify this to delete the node where Book Id='2'?
Code:
<?xml version='1.0'?>
<Collection>
<Book Id='1'>
<Title>Principle of Relativity</Title>
<Author>Albert Einstein</Author>
<Genre>Physics</Genre>
</Book>
<Book Id='2'>
<Title>Cosmos</Title>
<Author>Carl Sagan</Author>
<Genre>Cosmology</Genre>
</Book>
</Collection>
I want to write a C# method that will delete the Book node with the Id='2'.
I have the following code:
Code:
XmlDocument doc = new XmlDocument();
doc.Load("test.xml");
XmlNodeList nodeList = doc.SelectNodes("//Collection");
foreach (XmlNode node in nodeList)
{
node.RemoveChild(node.SelectSingleNode("Book"));
}
doc.PreserveWhitespace = true;
XmlTextWriter writer = new XmlTextWriter("test.xml", Encoding.Unicode);
doc.WriteTo(writer);
writer.Close();
which removes the first node with the id 'Book'. Please can someone tell me how i can modify this to delete the node where Book Id='2'?