How to Create a XML File Using XmlTextWriter

Author: Surama Hotta 
XmlTextWriter Class allows you to Write XML to a file.You can use the inbuilt properties and methods of the XmlTextWriter class to create a xml file. XmlTextWriter Class provides a way to generating a XML Document/File.
1. Create a XmlTextWriter Object.
2. Pass the Xml File name and encoding type parameter through the Object.If encoding parameter is set to Nothing, then default encoding will be "UTF-8".
      XmlTextWriter writer  = new XMlTextWriter("fileName", null);

3. Indent Xml Document: Use Formatting Property to automatically format the XML File.
      writer.Formatting = Formatting.Indented;

4.Use Following essential Methods as per your requirements.

I. WriteStartDocument: This is the very first method of XMLTextWriter object to open new xml document with xml declaration of version 1.0.

IIWriteStartElement: This method adds an xml tag inside the xml file. It takes the tag name as a Input.
          It adds the Student as a tag inside the xml file.

III. WriteStartAttribute: This method adds an attribute to the Created elements. It takes attribute name, xml namespace and prefix string as inputs. We can use xml namespace and prefix string as blank string.
      writer.WriteStartAttribute(" ", "id" " ");     
          It adds the attribute 'id' to the student tag.

IV. WriteString: This method writes a text context. This can contain the value of the attribute with xml tag.
          It sets the id with the value "1"

V.WriteElementString: Write an element with the specified local name and value.
      writer.WriteElementStrine("FirstName", "Monali");          
          It adds the FirstName tag with value Monali.

VI.WriteEndAttribute: This method closes the previously added attribute. 
          It closes the attribute id.

VII. WriteEndElement: It closes one element. If more then one element is present, then it closes the inner one.
          It closes the Student tag.

VIII. WriteComments: This method is used to give specific comments while creating the xml file. It takes the Comment string as its input.
      writer.WriteComment("This is the xml file creation using XmlTextWriter");
          This adds the comment in the XML file.

IX. WriteEndDocument: This is the last method which is used to close the Xml document.
          This closes the xml file.
In Dynamix Ax you need to add 

X. Flush: This method flushes whatever is in the buffer to the underlying streams and also flushes the underlying streams.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.