Writing A New XML File
Here you will learn how to create a new XML file, with nodes, elements, comments and attributes. First, declare
a new XmlTextWriter which will do most of the work. Notice we will declare Imports System.Xml at the
very top of the code file.
Declarations
Imports System.Xml
Code
'Declare an XmlTextWriter
Dim xmlwrt As New XmlTextWriter(Server.MapPath("~/newxmlfile.xml"), Encoding.UTF8)
xmlwrt.WriteStartDocument()
File<?xml version="1.0" encoding="utf-8"?>
Now we will start creating some useful stuff, some nodes and elements (not sure what the difference is
to be honest), and a comment. To start, lets write the root node and a child.
Code
xmlwrt.WriteComment("Test comment")
xmlwrt.WriteStartElement("xmlroot")
xmlwrt.WriteStartElement("firstchild")
File
<?xml version="1.0" encoding="utf-8"?>
<!--Test comment-->
<xmlroot>
<firstchild>
Next, lets write some data elements
Code
xmlwrt.WriteStartElement("title")
xmlwrt.WriteString("New XML File")
xmlwrt.WriteEndElement()
xmlwrt.WriteStartElement("desc")
xmlwrt.WriteString("This is an example xml file")
xmlwrt.WriteEndElement()
xmlwrt.WriteEndElement()
File
<?xml version="1.0" encoding="utf-8"?>
<xmlroot>
<firstchild>
<title>New XML File</title>
<desc>This is an example xml file</desc>
</firstchild>
So now lets try some other useful ways of storing data, attributes, and CDATA sections.
Code
xmlwrt.WriteStartElement("secondchild")
xmlwrt.WriteAttributeString("attr1", "value1")
xmlwrt.WriteAttributeString("attr2", "value2")
xmlwrt.WriteCData("cdata sections will not be parsed, so what you see here will
be displayed exactly")
xmlwrt.WriteEndElement()
xmlwrt.WriteEndElement()
xmlwrt.WriteEndDocument()
xmlwrt.Close()
File
<?xml version="1.0" encoding="utf-8"?>
<!--Test comment-->
<xmlroot>
<firstchild>
<title>New XML File</title>
<desc>This is an example xml file</desc>
</firstchild>
<secondchild attr1="value1" attr2="value2">
<![CDATA[cdata sections will not be parsed, so what you see here will be
displayed exactly]]>
</secondchild>
</xmlroot>
So there you go, a programmatically created xml file with comments, nodes, elements and attributes, easy.
Now lets see how you might use it.
Next: Reading An XML File