0

I tried several different approaches and cannot seem to deserialize an XML into a list of classes. This is what my XML looks like:

<?xml version="1.0" encoding="utf-8"?>
<EmployeeDataList>
  <EmployeeData>
    <IsActive>true</IsActive>
    <Id>123456</Id>
    <FullName>JOHN SMITH</FullName>
  </EmployeeData>
  <EmployeeData>
    <IsActive>true</IsActive>
    <Id>998822</Id>
    <FullName>BILL SMITH</FullName>
  </EmployeeData>
</EmployeeDataList>

I always get the first node of employee lists so my .NET code looks like:

Dim empDatas = xdoc.Elements("EmployeeDataList")
Dim xempDataList As XElement = empDatas(0)

Dim serXml As New XmlSerializer(GetType(List(Of EmployeeData)))
Dim empDataList As List(Of EmployeeData) = CType(serXml.Deserialize(xempDataList.CreateReader), List(Of EmployeeData))
Debug.Print("EmployeeDatas count={0}", empDataList.Count)

and my class looks like:

<Serializable>
Public Class EmployeeData
    Public IsActive As Boolean
    Public Id As String
    Public FullName As String
End Class

The result of this is an exception

System.InvalidOperationException: There is an error in XML document (0, 0). ---> System.InvalidOperationException: <EmployeeDataList xmlns=''> was not expected.

Just not sure where I am going wrong.

sinDizzy
  • 1,300
  • 7
  • 28
  • 60
  • 1
    1. You have no root element in your XML 2. There is missung a `>` after each EmployeeDataList – Alex B. Nov 04 '20 at 07:08
  • that was a typo. its been fixed. – sinDizzy Nov 04 '20 at 16:43
  • You have two top level elements. XML can only have one root element. You'll need to wrap those ``s in a containing element or your document is not parseable as XML. Alternatively, could the contents of those `` elements be merged? Seems like that's what your code expects. – Jacob Nov 04 '20 at 16:50
  • I guess what I am saying is that I can get that first block no problem. The error happens on serXml.Deserialize. – sinDizzy Nov 04 '20 at 17:30
  • It's not XML, so you can't deserialize it as XML. Make it valid XML and then you can process it as XML. – Jacob Nov 04 '20 at 18:07
  • ok I've updated it. same error with deserializing the list if classes. – sinDizzy Nov 04 '20 at 19:06

1 Answers1

0

Ok so I found an answer here Is it possible to deserialize XML into List<T>?

I encapsulated the list trivially so that I could give it a name other than the default ArrayOfEmployeeData.

<Serializable>
Public Class EmployeeDataList
    <XmlElement("EmployeeData")>'Note: No 's' so its singular and NOT plural
    Public Property EmployeeDatas As List(Of EmployeeData)
End Class

then to deserialize

Dim xempDataList As XElement = empDatas(0)
Dim serXml As New XmlSerializer(GetType(EmployeeDataList))
Dim empDataList As EmployeeDataList = CType(serXml.Deserialize(xempDataList.CreateReader), EmployeeDataList)
Debug.Print("EmployeeDatas count={0}", empDataList.EmployeeDatas.Count)

and that seems to work great.

sinDizzy
  • 1,300
  • 7
  • 28
  • 60