How to write to an XML file

Writing to XML files is quite easy in ASP.NET as there are so many objects prepared for you -- you just need the syntax on how to use them. This code shows you how to write a simple member XML file.

<%@Page Language="VB" Debug="True" %>
<%@Import Namespace="System.XML" %>
<%@ Import Namespace="System.IO" %>

<script language="vb" runat="server">
Sub Page_Load()
   Dim strCurrentPath As String = Request.PhysicalPath
   Dim strXMLPath As String = Left(strCurrentPath, InStrRev(strCurrentPath, "\")) & "members3.xml"
   Dim objXMLWriter As XmlTextWriter
   Try
       objXMLWriter = New XmlTextWriter(strXMLPath, Nothing)
       outDocURL.innerHTML = "Writing to file: <b>" & strXMLPath & "</b>"
   Catch objError As Exception
       outError.innerHTML = "<b>* Error while accessing document</b>.<br />" & objError.Message & "<br />" & objError.Source
       Exit Sub
   End Try
   objXMLWriter.Formatting = Formatting.Indented
   objXMLWriter.Indentation = 3
   objXMLWriter.WriteStartDocument()
   objXMLWriter.WriteComment("Created on " & Now())
   objXMLWriter.WriteStartElement("members")
   objXMLWriter.WriteStartElement("member")
   objXMLWriter.WriteAttributeString("position", "regular")
   Dim intYears As Integer = 4
   objXMLWriter.WriteAttributeString("years", intYears.ToString("G"))
   objXMLWriter.WriteElementString("Address", "2374 Ash St.")
   Dim datBirthday As DateTime = #03/05/2000#
   objXMLWriter.WriteElementString("birthday", datBirthday.ToString("yyyy-MM-dd"))
   Dim intContributions As Integer = 23443
   objXMLWriter.WriteElementString("contributions", intContributions.ToString("G"))
   Dim blnLocal As Boolean = True
   objXMLWriter.WriteElementString("local", blnLocal.ToString())
   objXMLWriter.WriteEndElement()
   objXMLWriter.WriteEndElement()
   objXMLWriter.Flush()
   objXMLWriter.Close()
   Dim strXMLResult As String
   Dim objSR As StreamReader = File.OpenText(strXMLPath)
   strXMLResult = objSR.ReadToEnd()
   objSR.Close
   objSR = Nothing
   outResults.innerHTML = "<pre>" & Server.HtmlEncode(strXMLResult) & "<pre>"
End Sub
</script>


<html>
<body bgcolor="#ffffff">

<div id="outDocURL" runat="server"></div>
<div id="outError" runat="server"> </div>
<div id="outResults" runat="server"></div>

</body>
</html>

You might also like...

Comments

Edward Tanguay Edward Tanguay updates his personal web site tanguay.info weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The question of whether computers can think is just like the question of whether submarines can swim.” - Edsger W. Dijkstra