VB.NET || How To Serialize & Deserialize XML Using VB.NET
The following is a module with functions which demonstrates how to serialize and deserialize XML using VB.NET.
The following generic functions use System.Xml.Serialization to serialize and deserialize an object.
Note: Don’t forget to include the ‘Utils Namespace‘ before running the examples!
1. Serialize – Integer Array
The example below demonstrates the use of ‘Utils.Xml.Serialize‘ to serialize an integer array to xml.
The optional function parameter allows you to specify the System.Xml.Serialization.XmlRootAttribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
' Serialize - Integer Array ' Declare array of integers Dim numbers = New Integer() {1987, 19, 22, 2009, 2019, 1991, 28, 31} ' Optional: Create an XmlRootAttribute overloaded constructor and set its namespace. Dim myXmlRootAttribute = New System.Xml.Serialization.XmlRootAttribute("OverriddenRootElementName") With { .Namespace = "http://www.microsoft.com" } ' Serialize to XML Dim numbersXml = Utils.Xml.Serialize(numbers) ' Display XML Debug.Print(numbersXml) ' expected output: ' <?xml version="1.0"?> ' <ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> ' <int>1987</int> ' <int>19</int> ' <int>22</int> ' <int>2009</int> ' <int>2019</int> ' <int>1991</int> ' <int>28</int> ' <int>31</int> ' </ArrayOfInt> |
2. Serialize – String List
The example below demonstrates the use of ‘Utils.Xml.Serialize‘ to serialize a list of strings to xml.
The optional function parameter allows you to specify the System.Xml.Serialization.XmlRootAttribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
' Serialize - String List ' Declare list of strings Dim names = New List(Of String) From { "Kenneth", "Jennifer", "Lynn", "Sole" } ' Serialize to XML Dim namesXml = Utils.Xml.Serialize(names) ' Display XML Debug.Print(namesXml) ' expected output: ' <?xml version="1.0"?> ' <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> ' <string>Kenneth</string> ' <string>Jennifer</string> ' <string>Lynn</string> ' <string>Sole</string> ' </ArrayOfString> |
3. Serialize – Custom Object List
The example below demonstrates the use of ‘Utils.Xml.Serialize‘ to serialize a list of custom objects to xml.
The optional function parameter allows you to specify the System.Xml.Serialization.XmlRootAttribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
' Serialize - Custom Object List <System.Xml.Serialization.XmlRoot(ElementName:="Inventory")> ' Optional Public Class Inventory <System.Xml.Serialization.XmlArray(ElementName:="Parts")> ' Optional Public Property Parts As List(Of Part) End Class Public Class Part <System.Xml.Serialization.XmlElement(ElementName:="PartName")> ' Optional Public Property PartName As String <System.Xml.Serialization.XmlElement(ElementName:="PartId")> ' Optional Public Property PartId As Integer End Class ' Declare list of objects Dim inventory = New Inventory With { .Parts = New List(Of Part) From { New Part With { .PartName = "crank arm", .PartId = 1234 }, New Part With { .PartName = "chain ring", .PartId = 1334 }, New Part With { .PartName = "regular seat", .PartId = 1434 }, New Part With { .PartName = "banana seat", .PartId = 1444 }, New Part With { .PartName = "cassette", .PartId = 1534 }, New Part With { .PartName = "shift lever", .PartId = 1634 }} } ' Serialize to XML Dim inventoryXml = Utils.Xml.Serialize(inventory) ' Display XML Debug.Print(inventoryXml) ' expected output: ' <?xml version="1.0"?> ' <Inventory xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ' <Parts> ' <Part> ' <PartName>crank arm</PartName> ' <PartId>1234</PartId> ' </Part> ' <Part> ' <PartName>chain ring</PartName> ' <PartId>1334</PartId> ' </Part> ' <Part> ' <PartName>regular seat</PartName> ' <PartId>1434</PartId> ' </Part> ' <Part> ' <PartName>banana seat</PartName> ' <PartId>1444</PartId> ' </Part> ' <Part> ' <PartName>cassette</PartName> ' <PartId>1534</PartId> ' </Part> ' <Part> ' <PartName>shift lever</PartName> ' <PartId>1634</PartId> ' </Part> ' </Parts> ' </Inventory> |
4. Deserialize – Integer Array
The example below demonstrates the use of ‘Utils.Xml.Deserialize‘ to deserialize xml to an integer array.
The optional function parameter allows you to specify the System.Xml.Serialization.XmlRootAttribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
' Deserialize - Integer Array ' Declare Xml array of integers Dim numbersXml = $"<?xml version=""1.0""?> <ArrayOfInt xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <int>1987</int> <int>19</int> <int>22</int> <int>2009</int> <int>2019</int> <int>1991</int> <int>28</int> <int>31</int> </ArrayOfInt> " ' Optional: Create an XmlRootAttribute overloaded constructor and set its namespace. Dim myXmlRootAttribute = New System.Xml.Serialization.XmlRootAttribute("OverriddenRootElementName") With { .Namespace = "http://www.microsoft.com" } ' Deserialize from XML to specified type Dim numbers = Utils.Xml.Deserialize(Of Integer())(numbersXml) ' Display the items For Each item In numbers Debug.Print($"{item}") Next ' expected output: ' 1987 ' 19 ' 22 ' 2009 ' 2019 ' 1991 ' 28 ' 31 |
5. Deserialize – String List
The example below demonstrates the use of ‘Utils.Xml.Deserialize‘ to deserialize xml to a list of strings.
The optional function parameter allows you to specify the System.Xml.Serialization.XmlRootAttribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
' Deserialize - String List ' Declare Xml array of strings Dim namesXml = $"<?xml version=""1.0""?> <ArrayOfString xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <string>Kenneth</string> <string>Jennifer</string> <string>Lynn</string> <string>Sole</string> </ArrayOfString> " ' Deserialize from XML to specified type Dim names = Utils.Xml.Deserialize(Of List(Of String))(namesXml) ' Display the items For Each item In names Debug.Print($"{item}") Next ' expected output: ' Kenneth ' Jennifer ' Lynn ' Sole |
6. Deserialize – Custom Object List
The example below demonstrates the use of ‘Utils.Xml.Deserialize‘ to deserialize xml to a list of objects.
The optional function parameter allows you to specify the System.Xml.Serialization.XmlRootAttribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
' Deserialize - Custom Object List <System.Xml.Serialization.XmlRoot(ElementName:="Inventory")> ' Optional Public Class Inventory <System.Xml.Serialization.XmlArray(ElementName:="Parts")> ' Optional Public Property Parts As List(Of Part) End Class Public Class Part <System.Xml.Serialization.XmlElement(ElementName:="PartName")> ' Optional Public Property PartName As String <System.Xml.Serialization.XmlElement(ElementName:="PartId")> ' Optional Public Property PartId As Integer End Class ' Declare Xml array of objects Dim inventoryXml = $"<?xml version=""1.0""?> <Inventory xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""> <Parts> <Part> <PartName>crank arm</PartName> <PartId>1234</PartId> </Part> <Part> <PartName>chain ring</PartName> <PartId>1334</PartId> </Part> <Part> <PartName>regular seat</PartName> <PartId>1434</PartId> </Part> <Part> <PartName>banana seat</PartName> <PartId>1444</PartId> </Part> <Part> <PartName>cassette</PartName> <PartId>1534</PartId> </Part> <Part> <PartName>shift lever</PartName> <PartId>1634</PartId> </Part> </Parts> </Inventory> " ' Deserialize from XML to specified type Dim inventory = Utils.Xml.Deserialize(Of Inventory)(inventoryXml) ' Display the items For Each item In inventory.Parts Debug.Print($"{item.PartId} - {item.PartName}") Next ' expected output: ' 1234 - crank arm ' 1334 - chain ring ' 1434 - regular seat ' 1444 - banana seat ' 1534 - cassette ' 1634 - shift lever |
7. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 16, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Namespace Xml Public Module modXml ''' <summary> ''' Serializes the specified value to XML ''' </summary> ''' <param name="value">The value to serialize</param> ''' <param name="root">The XmlRootAttribute that represents the XML root element</param> ''' <returns>The value serialized to XML</returns> Public Function Serialize(Of T)(value As T _ , Optional root As System.Xml.Serialization.XmlRootAttribute = Nothing) As String Dim xml = String.Empty Dim type = If(value IsNot Nothing, value.GetType, GetType(T)) Dim serializer = New System.Xml.Serialization.XmlSerializer(type:=type, root:=root) Using stream = New System.IO.MemoryStream serializer.Serialize(stream, value) xml = GetStreamText(stream) End Using Return xml End Function ''' <summary> ''' Deserializes the specified value from XML to Object T ''' </summary> ''' <param name="value">The value to deserialize</param> ''' <param name="root">The XmlRootAttribute that represents the XML root element</param> ''' <returns>The value deserialized to Object T</returns> Public Function Deserialize(Of T)(value As String _ , Optional root As System.Xml.Serialization.XmlRootAttribute = Nothing) As T Dim obj As T = Nothing Dim serializer = New System.Xml.Serialization.XmlSerializer(type:=GetType(T), root:=root) Using stringReader = New System.IO.StringReader(value) Using xmlReader = System.Xml.XmlReader.Create(stringReader) obj = CType(serializer.Deserialize(xmlReader), T) End Using End Using Return obj End Function Public Function GetStreamText(stream As System.IO.Stream) As String Try TryResetPosition(stream) Dim stmReader = New System.IO.StreamReader(stream) Dim text = stmReader.ReadToEnd Return text Catch ex As Exception Throw Finally TryResetPosition(stream) End Try End Function Private Sub TryResetPosition(stream As System.IO.Stream) If stream.CanSeek Then stream.Position = 0 End If End Sub End Module End Namespace End Namespace ' http://programmingnotes.org/ |
8. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 16, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program <System.Xml.Serialization.XmlRoot(ElementName:="Inventory")> ' Optional Public Class Inventory <System.Xml.Serialization.XmlArray(ElementName:="Parts")> ' Optional Public Property Parts As List(Of Part) End Class Public Class Part Public Property PartName As String Public Property PartId As Integer End Class Sub Main(args As String()) Try ' Declare array of integers Dim numbers = New Integer() {1987, 19, 22, 2009, 2019, 1991, 28, 31} ' Create an XmlRootAttribute overloaded constructor and set its namespace. Dim myXmlRootAttribute = New System.Xml.Serialization.XmlRootAttribute("OverriddenRootElementName") With { .Namespace = "http://www.microsoft.com" } ' Serialize to XML Dim numbersXml = Utils.Xml.Serialize(numbers) ' Display XML Display(numbersXml) Display("") ' Declare list of strings Dim names = New List(Of String) From { "Kenneth", "Jennifer", "Lynn", "Sole" } ' Serialize to XML Dim namesXml = Utils.Xml.Serialize(names) ' Display XML Display(namesXml) Display("") ' Declare list of objects Dim inventory = New Inventory With { .Parts = New List(Of Part) From { New Part With { .PartName = "crank arm", .PartId = 1234 }, New Part With { .PartName = "chain ring", .PartId = 1334 }, New Part With { .PartName = "regular seat", .PartId = 1434 }, New Part With { .PartName = "banana seat", .PartId = 1444 }, New Part With { .PartName = "cassette", .PartId = 1534 }, New Part With { .PartName = "shift lever", .PartId = 1634 }} } ' Serialize to XML Dim inventoryXml = Utils.Xml.Serialize(inventory) ' Display XML Display(inventoryXml) Display("") ' Declare Xml array of integers Dim numbersXmlTest = $"<?xml version=""1.0""?> <ArrayOfInt xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <int>1987</int> <int>19</int> <int>22</int> <int>2009</int> <int>2019</int> <int>1991</int> <int>28</int> <int>31</int> </ArrayOfInt> " ' Deserialize from XML to specified type Dim numbersTest = Utils.Xml.Deserialize(Of Integer())(numbersXmlTest) ' Display the items For Each item In numbersTest Display($"{item}") Next Display("") ' Declare Xml array of strings Dim namesXmlTest = $"<?xml version=""1.0""?> <ArrayOfString xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <string>Kenneth</string> <string>Jennifer</string> <string>Lynn</string> <string>Sole</string> </ArrayOfString> " ' Deserialize from XML to specified type Dim namesTest = Utils.Xml.Deserialize(Of List(Of String))(namesXmlTest) ' Display the items For Each item In namesTest Display($"{item}") Next Display("") ' Declare Xml array of objects Dim inventoryXmlTest = $"<?xml version=""1.0""?> <Inventory xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""> <Parts> <Part> <PartName>crank arm</PartName> <PartId>1234</PartId> </Part> <Part> <PartName>chain ring</PartName> <PartId>1334</PartId> </Part> <Part> <PartName>regular seat</PartName> <PartId>1434</PartId> </Part> <Part> <PartName>banana seat</PartName> <PartId>1444</PartId> </Part> <Part> <PartName>cassette</PartName> <PartId>1534</PartId> </Part> <Part> <PartName>shift lever</PartName> <PartId>1634</PartId> </Part> </Parts> </Inventory> " ' Deserialize from XML to specified type Dim inventoryTest = Utils.Xml.Deserialize(Of Inventory)(inventoryXmlTest) ' Display the items For Each item In inventoryTest.Parts Display($"{item.PartId} - {item.PartName}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply