Search code examples
xmlvb.netxmlserializer

How to structure a class to output an attribute and a simple string in the same XML node


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.


Solution

  • 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.