How to use XMLTextWriter to create an XML document in VB.NET

You can create a XML document, by using the basic XmlTextWriter class. This class works like StreamWriter relative, except that it writes XML document instead of ordinary text file. You can follow the next process:

‘ Place the file in the App_Data subfolder of the current website. ‘ The System.IO.Path class makes it easy to build the full file name. Dim File As String = Path.Combine(Request.PhysicalApplicationPath, “App_Data\BooksList.xml”) Dim Fs As FileStream = New FileStream(File, FileMode.Create) Dim W As XmlTextWriter = New XmlTextWriter(Fs, System.Text.Encoding.Unicode)

– You create the entire XML document by calling the methods of the XmlTextWriter, in the right order. To start a document, you always begin by calling WriteStartDocument(). To end it, you call WriteEndDocument().

– The next step is writing the elements you need. You write elements in three steps. First, you write the start tag (like <Book>) by calling WriteStartElement(). Then you write attributes, elements, and text content inside. Finally, you write the end tag (like </Book>) by calling WriteEndElement().

– The methods you use always work with the current element. So if you call WriteStartElement() and follow it up with a call to WriteAttributeString(), you are adding an attribute to that element. Similarly, if you use WriteString(), you insert text content inside the current element, and if you use WriteStartElement() again, you write another element, nested inside the current element.

If you compile and execute the code the result is a file BooksList.xml. To check that your code worked, open the file in Internet Explorer, which automatically provides a collapsible view for XML documents: