System.NotSupportedException:同时从 XML 中删除节点节点

System.NotSupportedException: while removing node nodes from XML

我有一个绑定到 GridView 的 XML。在网格视图列中,我有一个删除行的按钮。但我不断收到:

System.NotSupportedException: Specified method is not supported.

protected void Remove(string itemValue)
{
    XDocument doc = XDocument.Load(Server.MapPath("~/ReportConfig.xml"));
    doc.Descendants("Report")
          .Where(p => (string)p.Attribute("ID") == itemValue)
    .FirstOrDefault().Remove();
}
protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName != "Delete") return;
    Remove(e.CommandArgument.ToString());
}

以及我正在尝试编辑的 XML:

<?xml version="1.0" encoding="utf-8" ?>
<Reports>
  <Report ID="1">
    <Name>Induction Status</Name>
    <Query>xyz</Query>
    <Details>User List</Details>
  </Report>
</Reports>

当不满足Where()条件时,FirstOrDefault()returns默认为null,然后Remove()会抛出异常,因为它无法处理 null 参考。

根据您的代码,当 e.CommandArgument.ToString()"1" 时,您的代码将正常工作,您最终将得到 XML <Reports />。但是当 e.CommandArgument.ToString()"1" 以外的任何值时,您的代码将抛出异常。将其更改为 .FirstOrDefault()?.Remove() 以避免异常:

doc.Descendants("Report")
   .Where(p => (string)p.Attribute("ID") == itemValue)
   .FirstOrDefault()?.Remove();