如何在特定的xml节点中选择子节点?

时间:2014-03-05 19:41:35

标签: c# asp.net xml

我想删除所选行并更新xml文件,然后使用更新的数据加载网格视图。调试时,我得到nodelist的空值。

这是我的xml文件

<?xml version="1.0" encoding="utf-8" ?>
<PERSONES>
  <person>
    <name>Dilan Perera</name>
    <age>22</age>
  </person>
  <person>
    <name>Thusitha Badde</name>
    <age>24</age>

  </person>
</PERSONES>

这是按钮点击事件。问题是我得到nodelist的空值

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{      
    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
    string age = row.Cells[2].Text.Trim(); // i get correct value for age here

    XmlDocument doc2 = new XmlDocument();
    doc2.Load(Server.MapPath("names.xml")); 
    XmlNode nodeList = doc2.SelectSingleNode(string.Format("PERSONES/person[@age='{0}']", age));

    doc2.DocumentElement.RemoveChild(nodeList);
    doc2.Save(Server.MapPath("names.xml"));

    getdata();   
}

2 个答案:

答案 0 :(得分:1)

xpath查询不正确,@表示属性,因此在年龄检查中删除@,然后它将过滤元素。

   protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
   {      
       GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
       string age = row.Cells[2].Text.Trim(); // i get correct value for age here

       XmlDocument doc2 = new XmlDocument();
       doc2.Load(Server.MapPath("names.xml")); 
       XmlNode nodeList = doc2.SelectSingleNode(string.Format("PERSONES/person[age='{0}']", age));

       doc2.DocumentElement.RemoveChild(nodeList);
       doc2.Save(Server.MapPath("names.xml"));

       getdata();   
   }

我刚测试了这个并且它有效。

答案 1 :(得分:0)

XmlDocument doc2 = new XmlDocument();
doc2.Load(Server.MapPath("names.xml")); 
XmlNode ageNode = doc2.SelectSingleNode(string.Format("//PERSONES/person/age[text() = '{0}']", age));
if (ageNode != null)
{
    var personNode = ageNode.ParentNode;

    doc2.DocumentElement.RemoveChild(personNode);
    doc2.Save(Server.MapPath("names.xml"));

}