Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.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# XElement.Remove()未完全删除具有特定属性的元素_C#_Xml_Linq - Fatal编程技术网

C# XElement.Remove()未完全删除具有特定属性的元素

C# XElement.Remove()未完全删除具有特定属性的元素,c#,xml,linq,C#,Xml,Linq,我有一个简单的命令,可以查看XML文件并删除属性与所提供字符串匹配的任何元素。但是,删除元素时会出现问题。这是我的密码: public async Task RemoveX(string name) { XDocument doc = XDocument.Load(path); var node = doc.Element("Reactions") .Elements("ReactionRole") .Where(x => x.Attribu

我有一个简单的命令,可以查看XML文件并删除属性与所提供字符串匹配的任何元素。但是,删除元素时会出现问题。这是我的密码:

public async Task RemoveX(string name)
{
    XDocument doc = XDocument.Load(path);
    var node = doc.Element("Reactions")
        .Elements("ReactionRole")
        .Where(x => x.Attribute("name").Value == name);

    node.Remove();
    using (var fs = File.OpenWrite(path))
    {
        doc.Save(fs);
    }
}
这是之前的XML文件

<?xml version="1.0" encoding="utf-8"?>
<Reactions>
  <ReactionRole name="test">
    <MessageID>699904390907035668</MessageID>
    <RoleID>663891376748101643</RoleID>
  </ReactionRole>
  <ReactionRole name="help">
    <MessageID>4518765213548745345</MessageID>
    <RoleID>456165487369178913</RoleID>
  </ReactionRole>
</Reactions>

699904390907035668
663891376748101643
4518765213548745345
456165487369178913
在我尝试删除属性为“test”的元素后,这里是同一个文件


4518765213548745345
456165487369178913
le name=“help”>
4518765213548745345
456165487369178913
我环顾四周,没有发现任何问题。有什么帮助吗?提前感谢。

使用
FileMode.OpenOrCreate
打开文件,该文件指定操作系统应打开文件(如果存在);否则,应创建一个新文件,如果存在,不要覆盖它。因此,为了保存我们的文档,我们必须覆盖现有文件,并使用
FileMode.Create
打开一个
FileStream
,该文件指定操作系统应创建一个新文件。如果文件已存在,则将覆盖该文件。
替换

using (var fs = File.OpenWrite(path))
{
   doc.Save(fs);
}


这个答案将从解释中受益…
文件。OpenWrite
不会覆盖该文件,只需将其更改为
文件。创建
,如果文件存在,它将覆盖该文件。虽然接受的答案是正确的,但更简单的解决方案是使用重载来接受文件名-
doc.Save(path)
using (var fs = File.OpenWrite(path))
{
   doc.Save(fs);
}
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
   doc.Save(fs);
}