2013-10-12 223 views
1

我想從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; 
      } 
     } 
    } 
} 

回答

1

你也可以做到這一點使用LINQ。例如,做這樣的事情:

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); 
+0

感謝您的選擇。 – deathismyfriend

+0

不客氣! –