简体   繁体   English

如何选择子节点,特别是xml节点?

[英]how to select child nodes in particular xml node?

I want to delete selected row and update the xml file and then load the grid view with updated data. 我想删除选定的行并更新xml文件,然后使用更新的数据加载网格视图。 When debugging I get null value for nodelist. 调试时,我会得到null的nodelist值。

This is my xml file 这是我的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>

Here is the button click event. 这是按钮单击事件。 The problem is I get null value for 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();   
}

The xpath query is incorrect, @ means attribute, so remove @ in the age check, then it will filter the element. 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();   
   }

I have just tested this and it works. 我刚刚对此进行了测试,并且可以正常工作。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM