lucky.expert lucky.expert - 1 month ago 6
Vb.net Question

How to serialize an object to XML with multiple identical sibling elements

I am trying to create the class structure that I can serialize into an XML file. Everything is working fine except for one section of my XML that must look like this:

<DeliveryAddress>
<AddressLine>123 Main st</AddressLine>
<AddressLine>Ste 99</AddressLine>
</DeliveryAddress>


What would my class structure look like to make this possible?

Public Class DeliveryAddress
Public Property AddressLine as new List(Of String)
End Class


The above works, but the address elements are just named 'String' instead of AddressLine when adding data like so:

Dim delAddr as new DeliveryAddress
delAddr.AddressLine.add("123 Main St")
delAddr.AddressLine.add("ste 99")


I feel like this should be simple but I'm not quite able to figure it out

Answer

Add "XmlElementAttribute" in front of the property. It works.

Public Class DeliveryAddress
    <XmlElementAttribute(IsNullable:=False)> _
    Public Property AddressLine As New List(Of String)
End Class

The output is:

   <?xml version="1.0" encoding="UTF-8"?>

-<DeliveryAddress xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<AddressLine>123 Main St</AddressLine>

<AddressLine>ste 99</AddressLine>

</DeliveryAddress>
Comments