Writing to XML (beginner)

M

Mike Whitaker

I need a bit of direction to help me get started, if possible.

I need to make an application that allows me to enter a value into a text
box, then on the click of a button, append the text & time to an XML file.

I am using VB.net through the Smart Device Application project, with Pocket
PC 3.

As a desktop app in VB.net I was able to use System.Xml.Serialization & got
it running (sort of...), however this appears to behave differently under
Smart Device projects. I am very new to this type of development, so you
could say that I am totaly lost at the moment.

Any pointers would be great.

Cheers,

Mike
 
B

Brian H

If you're appending to the file only, say for example a log file, you may be
best off opening the xmlfile file as an XmlDocument, use the DOM to assign
the main node to the root node you're appending to, create a document
fragment and append. For example, in one app I have a log file that keeps
500 log entries. I'll attach a code snippet below. Basically it just
writes an event with the event time as an attribute, and the text as the
element's data. There are optimizations that can be made to this if you're
hitting it a lot, but in my case it's only for
startup/shutdown/errorhandling so I didn't spend much time optimizing it. I
too have struggled a bit with the compact framework -- you take the big
brother's extra functionality for granted :)


Private Sub SaveXML(ByVal EntireMessage As String)


Dim LogPath As String = ApplicationPath & "log.xml" '
ApplicationPath defined at the module level
Dim TimeStamp As String = Now.ToString("MM/dd/yyyy HH:mm:ss")

Dim xmldoc As XmlDocument
Dim mainnode As XmlNode
Dim mainlist As XmlNodeList

Try

If Not System.IO.File.Exists(LogPath) Then

Dim fsw As System.IO.StreamWriter
fsw = New System.IO.StreamWriter(LogPath, True)
fsw.WriteLine("<log>")
fsw.WriteLine("</log>")
fsw.Close()
fsw = Nothing

End If

xmldoc = New XmlDocument
xmldoc.Load(LogPath)

mainlist = xmldoc.GetElementsByTagName("log")
mainnode = mainlist.Item(0)

While mainnode.ChildNodes.Count >= 500
'keep only N events in the log
mainnode.RemoveChild(mainnode.FirstChild)
End While

Dim docFrag As XmlDocumentFragment =
xmldoc.CreateDocumentFragment
docFrag.InnerXml = "<event time=""" & TimeStamp & """>" &
EntireMessage & "</event>"
mainnode.AppendChild(docFrag)
docFrag = Nothing

xmldoc.Save(LogPath)

Catch ex As Exception

Finally

xmldoc = Nothing
mainnode = Nothing
mainlist = Nothing

End Try

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top