Question xml serialization

groadsvb

Well-known member
Joined
Nov 13, 2006
Messages
75
Programming Experience
Beginner
I need to serialize a class with properties such as those below and below that is the needed xml result. I am not sure which attributes will get those results if I want to call the microsoft serializer. I do I need to build the xml string my self in code? Thanks.

Public Property Unit() as string = "100"

public Property UnitDesc as string = "Supervisor Unit"


Result needed for xml:

<Unit ID = "100">Supervisor Unit</Unit>
 
All properties of a type by default serialize as elements. So if you had those properties in a Something class you would get:
HTML:
<Something>
    <Unit>100</Unit>
    <UnitDesc>Supervisor Unit</UnitDesc>
</Something>
Attributes can be added to control output, Attributes That Control XML Serialization

To Unit property you need to add XmlAttribute attribute, specifying "ID" as name.
To UnitDesc property you need to add XmlText attribute.
If class is not named "Unit" (like example class Something) you need to add XmlRoot attribute to the class, specifying "Unit" as name.
An example (Imports System.Xml.Serialization):
    <XmlRoot("Unit")> Public Class Something
        <XmlAttribute("ID")> Public Property Unit() As String = "100"
        <XmlText()> Public Property UnitDesc() As String = "Supervisor Unit"
    End Class

A default instance of this type will serialize as requested:
HTML:
<Unit ID="100">Supervisor Unit</Unit>
When serializing you can use a XmlSerializerNamespaces that you add an empty prefix and namespace to set default empty namespace.
 
Back
Top