从 xml 中删除元素

Deleting elements from xml

我正在映射到 gridView asp,以下项目 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>

我试图删除一个特定的项目,当点击 gridView 的删除按钮时。

这是我的代码:

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

但什么也没发生。

我用而不是 Desendant :

xdoc.Elements("grammar")

请你检查我是否遗漏了什么。提前致谢。

尝试以下更改。从列表中删除项目时,您需要从列表末尾删除到开头,这样您就不会跳过项目。 Fir 示例,如果您有 4、5、6 并删除 5。6 变为 5,您最终跳过 6。您还缺少命名空间。

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