Ivalberto
Ivalberto

Reputation: 433

Deleting elements from xml

I'm mapping into a gridView asp, the items of the following xml :

<?xml version="1.0" encoding="utf-8"?>
<grammar xmlns="http://www.w3.org/2001/06/grammar" version="1.0" xml:lang="es-MX" mode="voice" tag-format="semantics/1.0" root="grmVoz">
  <rule id="grmVoz" scope="public">
    <ruleref uri="#rule1" />
    <tag>out.cxtag=rules.rule1;out.rule1=rules.rule1;</tag>
  </rule>
  <rule id="rule1">
    <tag>out='';</tag>
    <one-of>
      <item weight="1.0">Ivan Alberto<tag>out+="out1"</tag></item>
      <item weight="1.0">Ivan Alberto2<tag>out+="out2"</tag></item>
      <item weight="1.0">Ivan Alberto3<tag>out+="out3"</tag></item>
      <item weight="1.0">Ivan Alberto4<tag>out+="out4"</tag></item>
    </one-of>
  </rule>
</grammar>

I trying to delete a specific item, when click in the delete button of the gridView.

this is my code :

protected void gvGrammars_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
 GridViewRow row = (GridViewRow)gvGrammars.Rows[e.RowIndex];
        string valor = row.Cells[0].Text;
        XDocument xdoc = XDocument.Load(Server.MapPath("voiceGrammar.grxml"));
     xdoc.Descendants("grammar").Elements("rule")
        .Where(x => (string)x.Attribute("id") == "rule1").Elements("one-of").Elements("item").Where(y=> (string)y.Value == valor)
        .Remove();
xdoc.Save(Server.MapPath("voiceGrammar.grxml"));
    }

but nothing happend.

I used instead of Desendant :

xdoc.Elements("grammar")

please can you check if i missed something. Thanks in advance.

Upvotes: 0

Views: 93

Answers (1)

jdweng
jdweng

Reputation: 34421

Try changes below. When removing items from a list you need to remove from end of list to beginning so you do not skip items. Fir example if you have 4,5,6 and remove 5. 6 becomes 5 and you end up skipping 6. You were also missing the namespace.

protected void gvGrammars_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    GridViewRow row = (GridViewRow)gvGrammars.Rows[e.RowIndex];
    string valor = row.Cells[0].Text;
    XDocument xdoc = XDocument.Load(Server.MapPath("voiceGrammar.grxml"));
    XNamespace ns = xdoc.Root.GetDefaultNamespace();
    List<XElement> itemToDelete = xdoc.Descendants(ns + "rule")
        .Where(x => (string)x.Attribute("id") == "rule1")
        .Select(y => y.Descendants(ns + "item")
        .Where(z => z.FirstNode.ToString() == valor))
        .SelectMany(x => x).ToList();

    for (int i = itemToDelete.Count - 1; i >= 0; i--)
    {
        itemToDelete[i].Remove();
    }
    xdoc.Save(Server.MapPath("voiceGrammar.grxml"));
}

Upvotes: 1

Related Questions