Wednesday, April 15, 2015

Write data in XML file and Read form XML file

//.aspx file

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        id<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        name<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        city<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
   
    </div>
    </form>
</body>
</html>

//.cs file

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //fillgrid();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (File.Exists(Server.MapPath("test.xml")))
        {
            appendxml();
        }
        else
        {
            createxml();
        }
    }

    private void createxml()
    {
        string path = Server.MapPath("test.xml");

        XmlTextWriter xtr = new XmlTextWriter(path, null);

        xtr.WriteStartDocument();

        xtr.WriteStartElement("root");
        xtr.WriteStartElement("student");
        xtr.WriteElementString("id", TextBox1.Text);
        xtr.WriteElementString("name", TextBox2.Text);
        xtr.WriteElementString("city", TextBox3.Text);
        xtr.WriteEndElement();
        xtr.WriteEndElement();

        xtr.WriteEndDocument();
        xtr.Close();
        fillgrid();
    }

    private void fillgrid()
    {
        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath("test.xml"));
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }

    private void appendxml()
    {
        XmlDocument xdoc = new XmlDocument();
        xdoc.Load(Server.MapPath("test.xml"));

        XmlElement std = xdoc.CreateElement("student");
        XmlElement id = xdoc.CreateElement("id");
        XmlElement name = xdoc.CreateElement("name");
        XmlElement city = xdoc.CreateElement("city");

        XmlText idtext = xdoc.CreateTextNode(TextBox1.Text);
        id.AppendChild(idtext);
        XmlText nametext = xdoc.CreateTextNode(TextBox2.Text);
        name.AppendChild(nametext);
        XmlText citytext = xdoc.CreateTextNode(TextBox3.Text);
        city.AppendChild(citytext);

        std.AppendChild(id);
        std.AppendChild(name);
        std.AppendChild(city);

        xdoc.DocumentElement.AppendChild(std);
        xdoc.Save(Server.MapPath("test.xml"));

        fillgrid();

    }

No comments:

Post a Comment