我想從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;
}
}
}
}
這很好用謝謝。 – deathismyfriend