4

Given the XML:

<?xml version="1.0" encoding="UTF-8"?>
<Response Version="3">
  <Status StatusCode="Test">Some Value</Status>
</Response>

What is the correct way to structure the Status class so that the System.Xml.Serialization.XmlSerializer will parse the given XML into the status class correctly?

I am currently receiving this structure of XML from a third party and there is no chance that they will change the formatting.

My attempt at the response class looks like:

<XmlRoot(ElementName:="Response")> Public Class clsResponse
    <XmlAttribute(AttributeName:="Version"), DefaultValue(0)> Public Property intVersion() As Integer
    <XmlElement(ElementName:="Status", Type:=GetType(clsStatus), Order:=2)> Public Property strStatus() As clsStatus
End Class

And the status class:

<XmlRoot(ElementName:="Status")> Public Class clsStatus
    <XmlAttribute(AttributeName:="StatusCode")> Public Property strStatusCode() As String
    <XmlElement(ElementName:="Status", Order:=1)> Public Property strStatus() As String
End Class

Unfortunately this is resulting in the strStatus always being blank. All the examples I've been able to find online do not have a string value in the <Status> node, there are always sub nodes that make up the contents of the equivalent to the <Status> node.

Note: I've cut out a bunch of stuff from the XML and the code in an attempt to only include the relevant pieces. If I've cut out too much please let me know and I will supply any other needed information.

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75
Mike_OBrien
  • 1,395
  • 15
  • 34
  • 1
    Take a look at [Using XmlSerializer to create an element with attributes and a value but no sub-element](http://stackoverflow.com/a/3524289/3744182) which says how to do it in c# using the `[XmlText]` attribute... and here's a vb.net version of the same answer: [Class to serialise/deserialise xml file](https://stackoverflow.com/q/22589110/3744182). – dbc Apr 10 '18 at 20:47
  • 1
    Possible duplicate of [Class to serialise/deserialise xml file](https://stackoverflow.com/questions/22589110/class-to-serialise-deserialise-xml-file) – dbc Apr 10 '18 at 20:47

1 Answers1

1

You need to add another class for Status element, since it contains more than one member.

Public Class Response

    <XmlAttribute> Public Version As Integer
    Public Status As Status

End Class

Public Class Status

    <XmlAttribute> Public StatusCode As String
    <XmlText> Public Text As String

End Class

You can use properties as well as rename members as needed and decorate them with output names in xml attributes.

PavlinII
  • 1,061
  • 1
  • 7
  • 12