How to write to an 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>




Windows Live Spaces is here! It's easy to create your own personal Web site.
Check it out!

No comments: