Monday, April 11, 2011

Create XML file Dynamically Using ASP.Net C# On Server

Code in aspx
 <td>
                        <asp:TextBox runat="server" ID="txtFirstName" Text="manoranjan"></asp:TextBox>                   
                        <asp:TextBox runat="server" ID="txtLastName" Text="chennai"></asp:TextBox></td>

Code in aspx.cs

 string strMyXml = "<Employee>"+
                            "<firstName>"+txtFirstName.Text+"</firstName>"+
                            "<lastName>"+txtLastName.Text+"</lastName>"+
                          "</Employee>";

        XmlDocument xDoc = new XmlDocument();
        xDoc.LoadXml(strMyXml);
        //Here the xml is prepared and loaded in xml DOM.

        xDoc.Save(Server.MapPath("myNewXmlPerson.xml"));//instead of myNewXmlPerson , u can give any name.
        //The above line will save your XML.

        //This is one way to create xml. This method may not be very efficient to manage 500 data
        //You can go for using XmlDom instead to create xmlNodes.] Let me know if you want follow
        //xmlDom approach. To see its example you can read my blog post at
        //http://kavstech.blogspot.com/2009/07/create-xml-using-dom-and-use-xpath-to.html


        //Now if u want to read this xml and get data from it and assign their value to text box you can do like this


        txtFirstName.Text = "";
        txtLastName.Text = "";
        XmlDocument xDocRead = new XmlDocument();//I have taken this new object for your better understanding.

        xDocRead.Load(Server.MapPath("myNewXmlPerson.xml"));

        XmlNode xFN = xDocRead.SelectSingleNode("Employee/firstName");
        XmlNode xLN = xDocRead.SelectSingleNode("Employee/lastName");

        txtFirstName.Text = xFN.InnerText;
        txtLastName.Text = xLN.InnerText;
 CASE2..
---
1. Fill up dataset with query result:

    adp.Fill(ds, "Attendance");
2. Then create XmlDataDocument with dataset:
    XmlDataDocument xmlDoc = new XmlDataDocument(ds);

3. Finally you can save XmlDataDocument as xml file on server:

    xmlDoc.Save(Server.MapPath("~/Attendance.xml"));



Let me know if the above example works for you, if you have any dobt let me know.

No comments:

Post a Comment