How do I ensure that an empty class gets serialized?
-
Thursday, May 17, 2012 11:05 PM
How do I ensure that an empty class gets serialized? I have a generic list collection within a class that I want to be serialized even if its empty. I can do each of the elements with “<XmlElement(IsNullable:=True)>”, but that does not work at the class level.
For a class defined like this …
<Serializable()> _ Public Class class1 <XmlElement(IsNullable:=True)> _ Public day_of_week As String <XmlElement(IsNullable:=True)> _ Public hour_of_day As String Public id As Int32 Public classList As List(Of class2) End Class Public Class class2 <XmlElement(IsNullable:=True)> _ Public line1_data As String <XmlElement(IsNullable:=True)> _ Public line2_data As String End ClassThe xml serializer produces this …
<class1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <day_of_week>1</day_of_week> <hour_of_day xsi:nil="true" /> <id>1</id> <classList /> </class1>
I want it to produce this ...
<class1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <day_of_week>1</day_of_week> <hour_of_day xsi:nil="true" /> <id>1</id> <classList /> <class2 /> </class1>
Notice the empty "<class2>" element. I know that I should not need this, but the third party tool that consumes XML does not function properly without it.
Does anyone know how I can force the Serializer to create this empty element?
All Replies
-
Friday, May 18, 2012 12:16 AM
A class doesn't exist until you call its constructor. So simply
new class1
new class2
jdweng
- Proposed As Answer by Mike FengMicrosoft Contingent Staff, Moderator Monday, May 21, 2012 11:07 AM
- Unproposed As Answer by Mike FengMicrosoft Contingent Staff, Moderator Monday, May 21, 2012 11:07 AM
-
Friday, May 18, 2012 7:10 PM
My VB.NET is rusty but try
Public classList As New List(Of class2)
That will instantiate an empty collection.
This signature unintentionally left blank.
- Proposed As Answer by Mike FengMicrosoft Contingent Staff, Moderator Monday, May 21, 2012 11:07 AM
-
Monday, May 21, 2012 11:07 AMModerator
Hi Rnes,
Do you have any update?
Best regards,
Mike Feng
MSDN Community Support | Feedback to us
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
-
Monday, May 21, 2012 1:10 PM
Thanks for your replies. I thought I was instantiating everything, but I missed the empty class. I was instantiating the list but not the class within the list. See below.
Thanks all for your help.
Dim c1List As New List(Of class1) Dim c1 As New class1 Dim c2List As New List(Of class2) Dim c2 As New class2
c2List.Add(c2) <---missed this one.
c1.day_of_week = 1
c1.id = 1
c1.classList = c2List
c1List.Add(c1)results = ut.SerializeToString(c1) 'method to serialize using (System.Xml.Serialization.XmlSerializer)
- Marked As Answer by Mike FengMicrosoft Contingent Staff, Moderator Tuesday, May 22, 2012 3:09 AM

