通过Gridview控件插入期间,Xml Subchild节点出现在子节点之外

时间:2013-08-08 14:30:26

标签: c# asp.net xml gridview

我的网页包含一个带插入/更新/删除功能的GridView控件;它的数据存储在XML文件中。我面临的问题是当我插入一个新行时,子子节点(新插入的日期)在复制到xml文件时出现在它的子节点(** pos节点)之外:例如:

<root>
  <pos>
    <partNumbers>
      <partid>0</partid>
      <partnumber>796547</partnumber>
    </partNumbers>
    <partNumbers>
      <partid>3</partid>
      <partnumber>567890</partnumber>
    </partNumbers>
  </pos>
  <partNumbers>
    <partid>10</partid>
    <partnumber>129123</partnumber>
  </partNumbers>
</root>

...我的目标是让新插入的行保留在 节点内,如下所示:

<root>
      <pos>
        <partNumbers>
          <partid>0</partid>
          <partnumber>796547</partnumber>
        </partNumbers>
        <partNumbers>
          <partid>3</partid>
          <partnumber>567890</partnumber>
        </partNumbers>
         <partNumbers>
        <partid>10</partid>
        <partnumber>129123</partnumber>
      </partNumbers>
      </pos>
     </root>

以下是我的插入代码:

protected void gvPartNumber_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        if (e.CommandName == "insertXMLData")
        {
            string partid = ((TextBox)gvPartNumber.FooterRow.FindControl("txtPartIDInsert")).Text;
            string partnumber = ((TextBox)gvPartNumber.FooterRow.FindControl("txtPartNumberInsert")).Text;
            BindGridView();
            DataTable dtXMLInsert = (DataTable)gvPartNumber.DataSource;

            DataSet dsgvPartNumber = new DataSet();
            dsgvPartNumber.ReadXml(Server.MapPath("~/xml/storeUserInfo.xml"));
            DataRow drInsert = dsgvPartNumber.Tables["partNumbers"].NewRow();
            drInsert["partid"] = partid;
            drInsert["partnumber"] = partnumber;
            dsgvPartNumber.Tables["partNumbers"].Rows.Add(drInsert);
            dsgvPartNumber.WriteXml(Server.MapPath("~/xml/storeUserInfo.xml"));
            BindGridView();

        }
      }

我能不能指出我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

没有对此进行测试,但基于它在根目录下添加XML的事实,我会猜测以下行需要更改:

dsgvPartNumber.Tables["partNumbers"].Rows.Add(drInsert);

dsgvPartNumber.Tables["pos"].Rows.Add(drInsert);

编辑:

我们走了:

添加:

DataRow drParent = dsgvPartNumber.Tables["pos"].Rows[0];
drInsert.SetParentRow(drParent);

最终代码应为:

DataSet dsgvPartNumber = new DataSet();
dsgvPartNumber.ReadXml(Server.MapPath("~/xml/storeUserInfo.xml"));
DataRow drInsert = dsgvPartNumber.Tables["partNumbers"].NewRow();
drInsert["partid"] = partid;
drInsert["partnumber"] = partnumber;
DataRow drParent = dsgvPartNumber.Tables["pos"].Rows[0];
drInsert.SetParentRow(drParent);
dsgvPartNumber.Tables["partNumbers"].Rows.Add(drInsert);
dsgvPartNumber.WriteXml(Server.MapPath("~/xml/storeUserInfo.xml"));
BindGridView();