我想从 XML 文件中删除一个节点。
这是 XML 文件的样子。
<?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>
我希望它以这样的方式结束。
<?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>
这就是我到目前为止所拥有的。但这只会删除子节点。它不会删除节点。
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;
}
}
}
}