Amit Bhisikar
Amit Bhisikar

Reputation: 69

System.NotSupportedException: while removing node nodes from XML

I have an XML which is bound to GridView. In a grid view column I have a button to delete the row. but I keep getting:

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());
}

And the XML that I am trying to edit:

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

Upvotes: 1

Views: 118

Answers (1)

Racil Hilan
Racil Hilan

Reputation: 25351

When the Where() condition is not met, FirstOrDefault() returns the default which is null, and then Remove() will throw the exception because it cannot work on a null reference.

According to your code, when e.CommandArgument.ToString() is "1", then your code will work and you will end up with the XML <Reports />. But when e.CommandArgument.ToString() is any value other than "1", then your code will throw the exception. Change it to .FirstOrDefault()?.Remove() to avoid the exception:

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

Upvotes: 1

Related Questions