Pages

21 Aug 2013

How to write Xml file programmatically with ASP.NET XmlWriter

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Xml" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e)
    {
        string xmlFile = Request.PhysicalApplicationPath + @"App_Data\BookStore.xml";
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.ConformanceLevel = ConformanceLevel.Auto;
        settings.OmitXmlDeclaration = false;
        try
        {
            using (XmlWriter writer = XmlWriter.Create(xmlFile, settings))
            {
                writer.WriteStartDocument(false);
                writer.WriteComment("This is a comment.");
                writer.WriteStartElement("books");
                writer.WriteStartElement("book");
                writer.WriteElementString("id","1");
                writer.WriteElementString("name", "Apple Training Series: GarageBand 09");
                writer.WriteElementString("author", "Mary Plummer");
                writer.WriteElementString("price","$39.99");
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.Flush();
                Label1.Text = "File written successfully!";
                }
            }
        catch (Exception ex)
        {
            Label1.Text = "An Error Occured: " + ex.Message;
        }
    }
</script>
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>XmlWriter: How to write Xml file programmatically in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy; font-style:italic;">XML Example: Writing Xml File Programmatically</h2>
        <asp:Label  
             ID="Label1"
             runat="server"
             Font-Bold="false"
             ForeColor="PaleVioletRed"
             Font-Size="Large"
             Font-Names="Comic Sans MS"
             >
        </asp:Label>
    </div>
    </form>
</body>
</html>  

No comments:

Post a Comment