Reading and Writing XML content is important in any programming language. In this article, I will explain how an XML file can be written dynamically. I am going to describe two methods: one for showing xml content on to the console and another for writing xml contents to a .dat file.
.NET framework provides an XmlWriter class a static Create method that expects either a FileStream or stringwriter to write contents to a file and to show contents on the console respectively.
Once xmlwriter object is instantiated with stream object. It can further be populated with relevant information.
Let’s say we’ve the following XML structure to be written:
Ex:
- <?xml version="1.0" encoding="utf-8"?>
- <Person>
- <Employee>
- <Name>John</Name>
- <Address>London </Address>
- </Employee>
- </Person>
Standard methods are listed below to accomplish the task stated above:
xmlWriter.WriteStartElement: Writes out a start tag with the specified local name.
xmlWriter.WriteElementString: Writes an element containing a string value.
xmlWriter.WriteEndDocument: Closes any open elements or attributes and puts the writer back in the Start state.
- private static void Main(string[] args)
- {
-
- ShowXMLOnConsole();
-
- WriteDyanmicallyCreatedXmlToFile();
- Console.ReadKey();
- }
-
-
-
-
-
- private static void WriteDyanmicallyCreatedXmlToFile()
- {
- FileStream writer = new FileStream(@"c:\temp\xmlcontent.dat", FileMode.CreateNew);
-
- using(XmlWriter xmlWriter = XmlWriter.Create(writer))
- {
- xmlWriter.WriteStartElement("Person");
- xmlWriter.WriteStartElement("Employee");
- xmlWriter.WriteElementString("Name", "John");
- xmlWriter.WriteElementString("Address", "London");
-
- xmlWriter.WriteEndDocument();
-
- writer.Flush();
- }
-
- string xmlContent = writer.ToString();
-
- Console.WriteLine(xmlContent);
- }
-
- private static void ShowXMLOnConsole()
- {
- StringWriter writer = new StringWriter();
- using(XmlWriter xmlWriter = XmlWriter.Create(writer))
- {
- xmlWriter.WriteStartElement("Person");
- xmlWriter.WriteStartElement("Employee");
- xmlWriter.WriteElementString("Name", "John");
- xmlWriter.WriteElementString("Address", "London");
-
- xmlWriter.WriteEndDocument();
-
- writer.Flush();
- }
-
- string xmlContent = writer.ToString();
-
- Console.WriteLine(xmlContent);
- }
For more information on methods available, refer to Microsoft documentation: