letmecry
letmecry

Reputation: 21

Issue with xml to object c# using Xml.Serialization

I have an old xml response and I cannot map it to an object as I normally do.

<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://uat.api.sample.uk">
    <SOAP-ENV:Body>
        <ns1:directReportResponse xmlns:ns1="urn:Direct">
            <return xsi:type="SOAP-ENC:Array" SOAP-ENC:arrayType="tns:DirectResult[1]">
                <item xsi:type="tns:DirectResult">
                    <TMSReference xsi:type="xsd:string">sampleTMS</TMSReference>
                    <Postcode xsi:type="xsd:string">samplePostcode</Postcode>
                    <ExpectedDelivery xsi:type="xsd:string">2020-08-25</ExpectedDelivery>
                </item>
            </return>
        </ns1:directReportResponse>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

After follow andyrut, I can map it to custom type but still no value in an item obj

Upvotes: 1

Views: 317

Answers (1)

andyrut
andyrut

Reputation: 128

The generated class does not know that a "return" tag is an array of "item" elements. You simply need to make the following modifications to your C# class:

  1. Delete the class definition for Return.

  2. Mark the Return data member as a list/array of Item's. Change the Return data member in the DirectReportResponse to a list and decorate it like so:

    [XmlArray(ElementName="return", Namespace="")] [XmlArrayItem(ElementName="item", Namespace="")] public List<Item> Return { get; set; }

  3. There's a Type specified in the Item XML, so decorate your Item class by adding the following line above it:

    [XmlType(Namespace="http://uat.api.sample.uk", TypeName="DirectResult")]

You may need to tweak your C# class for the other specified types in the XML file.

Upvotes: 1

Related Questions