XmlTextWriter Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data. XmlTextWriter renders XML data to a string. This string remains in the memory of the C# program. XmlTextWriter is useful for in-memory generation of XML.
  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. // Creates an instance of the System.Xml.XmlTextWriter class using the specified file.
  4. XmlTextWriter textWriter = new XmlTextWriter(@"C:\xmlfile.xml", null);
  5. // Writes the XML declaration with the version "1.0".
  6. textWriter.WriteStartDocument();
  7. // Write comments
  8. textWriter.WriteComment("First Comment for XmlTextWriter Sample Example");
  9. // Write first element
  10. textWriter.WriteStartElement("Student");
  11. textWriter.WriteStartElement("Document", "Test", "RECORD");
  12. // Write next element Name
  13. textWriter.WriteStartElement("Name");
  14. textWriter.WriteString("Rajendra");
  15. textWriter.WriteEndElement();
  16. // Write element Address
  17. textWriter.WriteStartElement("Address");
  18. textWriter.WriteString("Bangalore");
  19. textWriter.WriteEndElement();
  20. // Write element Pincode
  21. textWriter.WriteStartElement("Pincode");
  22. textWriter.WriteString("560066");
  23. textWriter.WriteEndElement();
  24. // WriteChars
  25. char[] ch = new char[3];
  26. ch[0] = 'R';
  27. ch[1] = 'A';
  28. ch[2] = 'J';
  29. textWriter.WriteStartElement("Char");
  30. textWriter.WriteChars(ch, 0, ch.Length);
  31. textWriter.WriteEndElement();
  32. // Ends the document.
  33. textWriter.WriteEndDocument();
  34. // close writer
  35. textWriter.Close();
  36. }
Result
XML Text Writer