删除节点及其子节点

时间:2013-10-12 22:07:08

标签: c# xml

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

2 个答案:

答案 0 :(得分:3)

尝试使用XmlNode.RemoveChild

node.RemoveChild(movie);

答案 1 :(得分: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);