码迷,mamicode.com
首页 > Web开发 > 详细

asp.net 的xml数据增删改查

时间:2016-05-13 02:02:40      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

A.前台html页面


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <link href="handle/admin-style.css" rel="stylesheet" type="text/css" />
    <link href="handle/pop.css" rel="stylesheet" type="text/css" />
    <link href="handle/base.css" rel="stylesheet" type="text/css" />
    <script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
 

    <script type="text/javascript">
 


    function showmed() {
        document.getElementById(‘med‘).style.display = ‘block‘;
        document.getElementById(‘bg‘).style.display = ‘block‘;
    }

    function closemed() {
        document.getElementById(‘med‘).style.display = ‘none‘;
        document.getElementById(‘bg‘).style.display = ‘none‘;
    }

    function show() {
        alert(‘ok‘);
    }

    $("#Button4").bind("click", show);


 
    
    // 提示
    function showTip(id, msg) {
        $("#" + id).show().css({ "color": "red" });
        $("#" + id).html(msg);
        $("#" + id).show();
        setTimeout(function () {
            $("#" + id).hide();
        }, 3000);
    }


    //弹窗提示
    function mnTip(msg) {
        //$.dialog.tips("<div style=‘font-size:16px; padding:10px 10px;dispaly:block;‘>" + msg + "</div>", 2, "tips.gif");
        $(".pop-notice-off,.pop-text").remove();
        $("body").append("<div class=‘pop-notice-off‘><div class=‘pop-text‘></div></div>");
        $(".pop-text").text(msg);
        $(".pop-notice-off").show();
        setTimeout(function () {
            $(".pop-notice-off").hide();
            $(".pop-notice-off,.pop-text").remove();
        }, 2000);
    }

    function showCheckUI(s) {
        $("#check_" + s).slideToggle();
        $("#hidType").val(s);
    }

    $(document).ready(function () {

        $.each($("input[id$=‘_auto‘]"), function (i, rdo) {
            if ($(rdo).attr("checked") == "checked") {

                $(rdo).parent().next("table").show();



            }
            else {
                $(rdo).parent().next("table").hide();
                showTip("tip", "hello!");

            }
        });

        $("input[id$=‘_auto‘]").bind("click", function () {
            if ($(this).attr("checked") == "checked") {
                $(this).parent().next("table").show();
            }
        });

        $("input[id*=‘_Manual‘]").bind("click", function () {
            if ($(this).attr("checked") == "checked") {
                $(this).parent().prev("table").hide();
            }
        });
    });

</script>

</head>
<body>
    <form id="form1" runat="server">
    <div id="med">
      

        id:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><input id="Text1" type="text" />
        name:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        age:<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="add" onclick="Button1_Click"
            Width="41px"  />

                    <asp:Button ID="Button5" runat="server" Text="search"
     Width="41px" onclick="Button5_Click"  />

        

        <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
            Width="74%" CellPadding="3"
                     
                    BorderWidth="1px" DataKeyNames="id"
                    AutoGenerateColumns="false" PageSize="4"  
            RowStyle-HorizontalAlign="Center"
            onpageindexchanging="GridView1_PageIndexChanging"
            onrowcommand="GridView1_RowCommand" onrowdatabound="GridView1_RowDataBound"
           >
                    <Columns>
                
                    <asp:TemplateField ControlStyle-Width="10" HeaderText="选择">
                                <ItemTemplate>
                                    <asp:CheckBox ID="DeleteThis_new" onclick="javascript:CCA(this);" runat="server" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            
        <asp:BoundField DataField="id" HeaderText="id" SortExpression="id" ItemStyle-HorizontalAlign="Center"  />

            <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" ItemStyle-HorizontalAlign="Center"/>
        
            <asp:BoundField DataField="age" HeaderText="age" SortExpression="age" ItemStyle-HorizontalAlign="Center"  />
                         
                        
                    <asp:TemplateField HeaderText="操作">
                <ItemTemplate>

                   
                      <asp:ImageButton   ID="ImageButton2" runat="server" Text="编辑" CommandName="edi" CommandArgument=‘<%# Eval("id") %>‘ ImageUrl="~/Admin/images/编辑.jpg" />
                      
                     <asp:ImageButton   ID="ImageButton1" runat="server" Text="删除" CommandName="del" CommandArgument=‘<%# Eval("id") %>‘ ImageUrl="~/Admin/images/删除.jpg" />
                </ItemTemplate>
                
                </asp:TemplateField>
                        </Columns>
                         <PagerTemplate>
                第<asp:Label ID="lblCurrent" runat="server" Text=‘<%# ((GridView)Container.Parent.Parent).PageIndex+1%>‘></asp:Label>页
                共<asp:Label ID="lblTotal" runat="server" Text=‘<%# ((GridView)Container.Parent.Parent).PageCount%>‘></asp:Label>页
                <asp:LinkButton ID="lb_first" runat="server" CommandName="Page"  CommandArgument="First">首页</asp:LinkButton>
                <asp:LinkButton ID="lb_prev" runat="server" CommandName="Page" CommandArgument="Prev">上页</asp:LinkButton>
                <asp:LinkButton ID="lb_next" runat="server" CommandName="Page" CommandArgument="Next">下页</asp:LinkButton>
                <asp:LinkButton ID="lb_last" runat="server" CommandName="Page" CommandArgument="Last">末页</asp:LinkButton>
            </PagerTemplate>

                </asp:GridView>
</div>
        
    <div>
      

        id:<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
        name:<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
        age:<asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
        <asp:Button ID="Button2" runat="server" Text="edit" onclick="Button2_Click"
            Width="56px" />


        <asp:Button ID="Button3" runat="server" Text="Button" onclick="Button3_Click"
            Width="40px" />


         <asp:LinkButton ID="btnAddAdmin" CssClass="lin-01" runat="server" OnClick="btnAddAdmin_Click">添加管理员</asp:LinkButton>
</div>
<div id="bg">

 <div class="u-xzqx" id="menuChks" runat="server">


                        <asp:CheckBox ID="chkOrg" runat="server" Text="服务方管理" />
               
                  
                        <asp:CheckBox ID="chkRecruit" runat="server" Text="招聘方管理" />
                    
                   
                        <asp:CheckBox ID="chkJob" runat="server" Text="求职方管理" />
     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
     <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
 </div>


 </div>



    <div class="u-sh-cont">
            <dl>
                <dt>服务方审核设置</dt>
                <dd class="w-ms" id="title_Shop">
                   
                </dd>


                <dd class="w-98">
                    <a href="javascript:void(0)" onclick="showCheckUI(‘shop‘)" class="lin-02">修改</a></dd>



            </dl>

            <div class="u-sh-xg" name="checkUI" id="check_shop">

                <div class="title">
                    <input type="radio" name="rdo_shop" id="rdoShop_auto" value="MN_SHOP" />
                    自动审核 <span>注:运营方对用户开通服务的申请,在设置时间后自动审核。</span>
                </div>


                <table width="100%" border="0" cellspacing="5" cellpadding="0">
                    <tr>
                        <td width="22%" height="50" align="right">
                            发送消息间隔时间:
                        </td>
                        <td width="78%">
                            <select name="select" class="input-box w-230" id="selShop_Time">
                                <option value="0" >0</option>
                                <option value="1" >1分钟</option>
                                <option value="5" >5分钟</option>
                                <option value="20">20分钟</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td height="40" align="right">
                            消息内容:
                        </td>
                        <td>
                            <textarea name="textarea" id="txtShop_Content" cols="58" rows="5">
                           
                            </textarea>
                        </td>
                    </tr>
                </table>

                <div class="title">
                    <input type="radio" name="rdo_shop" id="rdoShop_Manual" value="MN_SHOP"  />
                    手动审核 <span>注:运营方对用户开通服务的申请逐一手动审核。</span>
                </div>
                <p>
                    <a href="javascript:void(0)" onclick="saveSetting(‘Shop‘,‘MN_SOCIETY‘)" class="lin-1 c_01">
                        确定</a></p>
            </div>

            
        </div>


        <div id="tip" style="height: 30px; line-height: 30px; ">
                </div>

                <input id="Button4" type="button" value="button" />
   
    </form>
</body>

</html>

B.XML文件

<?xml version="1.0" encoding="utf-8"?>
<students>
  <student key="zl">
    <id>88</id>
    <name>zl</name>
    <age>2</age>
  </student>
  <student key="wl">
    <id>66</id>
    <name>wl</name>
    <age>188</age>
  </student>

</students>

C后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Xml;
using System.IO;
using System.Collections;
public partial class t1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadGridView();
            Response.Write(GetCurrentWebRoot());

            foreach (var con in menuChks.Controls)
            {
                if (con is CheckBox)
                {
                    CheckBox chk = con as CheckBox;
                    chk.Checked = true;
                }
                else if (con is Label) {
                    Label lb = con as Label;
                   lb.Text ="aaaa";
                }
            }


        }
    }


    private void LoadGridView()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("aa.xml"));
        XmlNodeList list = doc.SelectNodes("students/student");
        ArrayList datalist = new ArrayList();
        foreach (XmlNode xnode in list)
        {
            CodeModel.Model.t1 t = new CodeModel.Model.t1();
            XmlNode bh = xnode.SelectSingleNode("id");
            XmlNode names = xnode.SelectSingleNode("name");
            XmlNode ages = xnode.SelectSingleNode("age");
            string id = bh.InnerText;
            string name = names.InnerText;
            string age = ages.InnerText;
            t.Id = id;
            t.Name = name;
            t.Age = age;
            datalist.Add(t);
        }
        GridView1.DataSource = datalist;
        GridView1.DataBind();  
        ////转换一个XML文件(本地\网络均可)为一个DataSet
        //DataSet ds = new DataSet();
        ////ds=XMLDataSetConverter.ConvertXMLFileToDataSet(Server.MapPath("xmltodataset.xml"));
        ////ds=XMLDataSetConverter.ConvertXMLFileToDataSet("http://news.baidu.com/n?cmd=1class=sportnewstn=rss");
        ////foreach(DataRowrowinds.Tables[0].Rows)
        ////{
        ////stringname=row["name"].ToString();
        ////stringage=row["age"].ToString();
        ////}

        //StringReader sreader = null;
        //XmlTextReader xtreader = null;
        //try
        //{
        //    XmlDocument doc = new XmlDocument();
        //    doc.Load(Server.MapPath("aa.xml"));

        //    sreader = new StringReader(doc.InnerXml);
        //    xtreader = new XmlTextReader(sreader);
        //    ds.ReadXml(xtreader);
        //}
        //catch (Exception)
        //{

        //    throw;

        //}
        //finally
        //{
        //    xtreader.Close();
        //    sreader.Close();
        //}
        //this.GridView1.DataSource = ds.Tables[0];
        //this.GridView1.DataBind();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        this.Add();
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        this.Update();

      

    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "edi")
        {
            //通过ID获取对象,给控件赋值
            string[] entity = this.GetEntity(e.CommandArgument.ToString()).Split(‘|‘);
            this.TextBox4.Text = entity[0];
            this.TextBox5.Text = entity[1];
            this.TextBox6.Text = entity[2];
        }
        else if (e.CommandName == "del")
        {
            //通过ID删除对象
            this.Delete(e.CommandArgument.ToString());
        }
    }


    private void Add()
    {
        string id = this.TextBox1.Text;
        string name = this.TextBox2.Text;
        string age = this.TextBox3.Text;

        //在第一个前面插入一条信息
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("aa.xml"));
        XmlNode students = doc.SelectSingleNode("students");

        XmlElement student = doc.CreateElement("student");
        student.SetAttribute("key", name);

        XmlElement ele_id = doc.CreateElement("id");
        ele_id.InnerText = id;

        //ele_id.SetAttribute("id", id
        student.AppendChild(ele_id);

        XmlElement ele_name = doc.CreateElement("name");
        ele_name.InnerText = name;
        student.AppendChild(ele_name);

        XmlElement ele_age = doc.CreateElement("age");
        ele_age.InnerText = age;
        student.AppendChild(ele_age);

        students.InsertBefore(student, students.FirstChild);

        doc.Save(Server.MapPath("aa.xml"));

        //重新加载GridView
        LoadGridView();

        this.TextBox1.Text = "";
        this.TextBox2.Text = "";
        this.TextBox3.Text = "";
    }
    private void Delete(string id)
    {
        //通过ID获取信息
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("aa.xml"));
        XmlNode students = doc.SelectSingleNode("students");
        foreach (XmlNode student in students.ChildNodes)
        {
            XmlNode node_id = student.FirstChild;
            if (node_id.InnerText == id)
            {
                student.ParentNode.RemoveChild(student);
            }
        }
        doc.Save(Server.MapPath("aa.xml"));
        LoadGridView();
    }
    private void Update()
    {
        string id = this.TextBox4.Text;
        string name = this.TextBox5.Text;
        string age = this.TextBox6.Text;

        //通过ID获取信息,然后更改信息
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("aa.xml"));
        XmlNode students = doc.SelectSingleNode("students");
        foreach (XmlNode student in students.ChildNodes)
        {
            XmlNode temp_node = student.FirstChild;
            if (temp_node.InnerText == id)
            {
                //第一种方式
                //student.RemoveAll();
                //XmlElement ele_id = doc.CreateElement("id");
                //ele_id.InnerText = id;
                //student.AppendChild(ele_id);

                //XmlElement ele_name = doc.CreateElement("name");
                //ele_name.InnerText = name;
                //student.AppendChild(ele_name);

                //XmlElement ele_age = doc.CreateElement("age");
                //ele_age.InnerText = age;
                //student.AppendChild(ele_age);

                //第二种方式
                student.ChildNodes[0].InnerText = id;
                student.ChildNodes[1].InnerText = name;
                student.ChildNodes[2].InnerText = age;

                doc.Save(Server.MapPath("aa.xml"));
                ClientScript.RegisterStartupScript(this.GetType(), "operate", "mnTip(‘修改成功‘);closemed();", true);


                break;
            }
        }

        LoadGridView();
    }
    private string GetEntity(string id)
    {
        string entity = "";
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("aa.xml"));
        XmlNode students = doc.SelectSingleNode("students");

        foreach (XmlNode student in students.ChildNodes)
        {
            XmlNode temp_node = student.FirstChild;
            if (temp_node.InnerText == id)
            {
                foreach (XmlNode item in student.ChildNodes)
                {
                    entity += item.InnerText + "|";
                }
                entity = entity.Substring(0, entity.Length - 1);
                break;
            }
        }
        return entity;
    }

 
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        int i = e.NewPageIndex;
        int j = i < 0 ? 0 : i;
        this.GridView1.PageIndex = j;
        LoadGridView();
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("style", "background:#FFF");
        }

       
    }
    public string GetCurrentWebRoot()
    {
        Uri uri = HttpContext.Current.Request.Url;
        string host = HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
        string webRoot = string.Format("{0}://{1}/", uri.Scheme, host);
        return webRoot;
        //string s = Request.Url.ToString();
        //return Request.Url.ToString();
        //Response.Redirect(Request.Url.ToString());
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "te", "alert(‘取消成功。‘)", true);

   
    }
    protected void btnAddAdmin_Click(object sender, EventArgs e)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "", "showmed();", true);
    }
    //查询
    protected void Button5_Click(object sender, EventArgs e)
    {
        string a = TextBox2.Text;
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("aa.xml"));
        XmlNodeList list = doc.SelectNodes("students/student[@key=‘"+a+"‘]");
        ArrayList datalist = new ArrayList();
        foreach (XmlNode xnode in list)
        {
            CodeModel.Model.t1 t = new CodeModel.Model.t1();
            XmlNode bh= xnode.SelectSingleNode("id");
            XmlNode names = xnode.SelectSingleNode("name");
            XmlNode ages = xnode.SelectSingleNode("age");
            string  id = bh.InnerText;
            string name = names.InnerText;
            string age = ages.InnerText;
            t.Id = id;
            t.Name = name;
            t.Age = age;
            datalist.Add(t);
        }
        GridView1.DataSource = datalist;
        GridView1.DataBind() ;  
 
    }
}









asp.net 的xml数据增删改查

标签:

原文地址:http://blog.csdn.net/wanglei_samrtfish/article/details/51346355

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!