Reputation: 2192
I want to remove a node from an XML file.
Here is what the XML file looks like.
<?xml version="1.0" encoding="utf-8"?>
<MovieData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Movie>
<Name>Death Race</Name>
<Type>Action</Type>
<Type>Adventure</Type>
<Rating>R</Rating>
<Disk>Blu-Ray</Disk>
</Movie>
<Movie>
<Name>Movie to be deleted</Name>
<Type>Action</Type>
<Type>Adventure</Type>
<Rating>R</Rating>
<Disk>Blu-Ray</Disk>
</Movie>
<Movie>
<Name>Death Race 2</Name>
<Type>Action</Type>
<Type>Adventure</Type>
<Rating>R</Rating>
<Disk>Blu-Ray</Disk>
<Time>time</Time>
</Movie>
</MovieData>
I want it to end up like this.
<?xml version="1.0" encoding="utf-8"?>
<MovieData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Movie>
<Name>Death Race</Name>
<Type>Action</Type>
<Type>Adventure</Type>
<Rating>R</Rating>
<Disk>Blu-Ray</Disk>
<Time>time</Time>
</Movie>
<Movie>
<Name>Death Race 2</Name>
<Type>Action</Type>
<Type>Adventure</Type>
<Rating>R</Rating>
<Disk>Blu-Ray</Disk>
<Time>time</Time>
</Movie>
</MovieData>
This is what I have so far. This only deletes the child nodes though. It doesn't delete the node.
XmlDocument doc = new XmlDocument();
doc.Load(movieListXML);
XmlNode node = doc.SelectSingleNode("/MovieData");
foreach (XmlNode movie in node.SelectNodes("Movie"))
{
if (movie != null)
{
if (name == movie["Name"].InnerText)
{
if ((this checks the data to make sure it is the one to be deleted))
{
movie.RemoveAll();
doc.Save(movieListXML);
return;
}
}
}
}
Upvotes: 1
Views: 189
Reputation: 3582
You can also do it using LINQ. For instance doing something like this:
var xDoc = XDocument.Load(xmlFile);
var movie = xDoc.Descendants("Movie")
.FirstOrDefault(e => e.Element("Name").Value == "Movie to be deleted");
if (movie != null) {
movie.Remove();
}
xDoc.Save(xmlFile);
Upvotes: 1