Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#:从xml中删除元素_C#_Xml_Linq_Linq To Xml - Fatal编程技术网

C#:从xml中删除元素

C#:从xml中删除元素,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,我从C#WinFroms级别对xml文件进行写入和读取。此外,我希望有一个函数来删除具有给定内容的元素。 我的xml格式: <libraryImages> <imageLink>*link1*</imageLink> <imageLink>*link2*</imageLink> </libraryImages> 例如,作为“pathToRemove”参数,我传递link1。 问题是-这不会从xml中删除此元

我从C#WinFroms级别对xml文件进行写入和读取。此外,我希望有一个函数来删除具有给定内容的元素。 我的xml格式:

<libraryImages>
    <imageLink>*link1*</imageLink>
    <imageLink>*link2*</imageLink>
</libraryImages>
例如,作为“pathToRemove”参数,我传递link1。 问题是-这不会从xml中删除此元素-因此,在我重新启动应用程序后,我的库的内容与以前一样,就好像我没有删除任何项目一样。
为什么这样不行?我浏览了许多stackoverflow问题,但什么也没找到。

在内存操作后,您应该更新xml文件:

// read file from disc and build in-memory representation of xml
var xdoc = XDocument.Load("XmlData.xml");

// modify in-memory representation
xdoc.Root.Elements("imageLink").Where(el => el.Value == pathToRemove).Remove();

// save modified representation back to disck
xdoc.Save("XmlData.xml");
// read file from disc and build in-memory representation of xml
var xdoc = XDocument.Load("XmlData.xml");

// modify in-memory representation
xdoc.Root.Elements("imageLink").Where(el => el.Value == pathToRemove).Remove();

// save modified representation back to disck
xdoc.Save("XmlData.xml");