Using XmlTextWriter to write XML Documents in .NET

You are currently viewing Using XmlTextWriter to write XML Documents in .NET

XML is one of the most popular topics these days. As the use of XML files is increasing, more and more developers want to learn how to write, read and consume XML documents from different programming languages. In the following tutorial, I will show you how you can use .NET Framework built in class XmlTextWriter to generate XML document in C#.

XmlTextWriter is one of many useful classes in System.Xml namespace, and it provides several useful methods to write a complete XML Document from scratch. Following form is simple ASP.NET web form asking user to input some data about the product. I will save this data in a separate XML document named Product.xml using XmlTextWriter object.

Following C# code is saving all the user input values in XML file.

protected void Button1_Click(object sender, EventArgs e)
    // Declare XmlTextWriter Object
    XmlTextWriter writer = null; 
        // Map file path to server physical root directory
        string filePath = Server.MapPath("~") + "\\Product.xml"; 
        // Create XmlTextWriter object with UTF32 Encoding

        writer = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
        writer.Formatting = Formatting.Indented;

        // Write Xml Declaration with version 1.0 

        // Write some comments 
        writer.WriteComment("Product Information");
        writer.WriteComment("Created On: " + DateTime.Now.ToString("dd-MMM-yyyy"));

        // Write Xml Document Root Element

        // Write attribute name and value to current Element 
        writer.WriteAttributeString("ProductID", TextBox1.Text);

        // Write Xml Element with Name and Inner Text
        writer.WriteElementString("ProductName", TextBox2.Text);
        writer.WriteElementString("ProductQuantity", TextBox3.Text);
        writer.WriteElementString("ProductPrice", TextBox4.Text);

        // Write Product Element closing Tag

        // Write End of Document 

        // Flush and Close Writer
    catch (Exception ex)
    { }

and here is the XML file generated by the above code.

READ ALSO:  Read Database Connection Strings from App.Config

This Post Has One Comment

  1. Ryan

    Very Simple, and to the point. Thank you. Got me into working with the XMLTextWriter right away, thank you

  2. Ryan

    Very Simple, and to the point. Thank you. Got me into working with the XMLTextWriter right away, thank you

  3. santosh kumar

    Thanks for give this type of tutorial,it is helpful for learning dotnet 2.0.

    Santosh Kumar

Leave a Reply