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;
            }
        }
    }
}
4

2 回答 2

3

尝试使用XmlNode.RemoveChild

node.RemoveChild(movie);
于 2013-10-12T22:10:31.330 回答
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);
于 2013-10-12T22:21:02.477 回答