How can one leverage XML without knowing much about XML?
The answer, as indicated in the previous posting, is XML serialization.
An XML serializer can be used to turn the data stored in objects into XML (and back from XML into objects). All the serializer needs to know is the class the objects are derived from. The serializer looks at the class definition and creates a corresponding XML structure. (The class has to be "serializable" and there are some cases where this automatic process will not work!)
Below is some example code in which an XML serializer is leveraged to save and load DataItem objects. The loadDataItems function reads the XML from a file and returns an array of DataItem objects. (DataItem could be replaced with Person, Patient, Contract, Restaurant, ... whatever your class is!). The saveDataItems function takes an array of DataItem objects and writes it to an XML file.
MH
--- Code ---
'need these imports at the top of your VB code!
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
...
Public Shared Function loadDataItems() As DataItem()
Dim mySerializer As XmlSerializer
Dim dataItems As DataItem()
Try
mySerializer = New XmlSerializer(GetType(DataItem()))
' To read the file, create a FileStream.
Dim myFileStream As FileStream = _
New FileStream(_filePath, FileMode.Open)
' Call the Deserialize method and cast to the object type.
dataItems = CType(mySerializer.Deserialize(myFileStream), DataItem())
Return dataItems
Catch ex As Exception
Return Nothing
End Try
End Function
Public Shared Function saveDataItems(ByVal dataItems As DataItem()) As Boolean
Dim mySerializer As XmlSerializer
Try
mySerializer = New XmlSerializer(GetType(DataItem()))
' To write to a file, create a StreamWriter object.
Dim myWriter As StreamWriter = _
New StreamWriter(_filePath)
mySerializer.Serialize(myWriter, dataItems)
myWriter.Close()
Return True
Catch ex As Exception
Return False
End Try
End Function