简体   繁体   中英

Specific Namespace in XML Deserialization fails

I looked for an issue but couldn't find the answer the this particular case, so here is the issue.

When trying to deserialize a xml string into a strong type object I got the following message:

System.InvalidOperationException: There is an error in XML document (1, 2). ---> System.InvalidOperationException: <GetPointOfDelivery_Out xmlns='urn:webbeB2B:webservices:v0'> was not expected.
    at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderGetPointOfDelivery_Out.Read16_GetPointOfDelivery_Out()

Although the class has to my opinion the correct namespace attribute value defined, being :

[XmlType(AnonymousType = true, Namespace = "urn:webbeB2B:webservices:v0")]
    public class GetPointOfDelivery_Out
    {
        [XmlElement("POD")]
        public POD[] POD
….
}

The source string looks like this:

<out:GetPointOfDelivery_Out xmlns:out="urn:webbeB2B:webservices:v0">
    <out:POD>
        <out:PODID>FT}UntwKNFlX0000h100Dm</out:PODID>
 ….
    </out:POD>
    <out:ErrorMessage>
        <out:MsgType>S</out:MsgType>
    </out:ErrorMessage>
</out:GetPointOfDelivery_Out>

I use the following code to deserialize the string

var xmlSerializer = new XmlSerializer(typeof(T));

            using (var textReader = new StringReader(xml))
            {
                return (T)xmlSerializer.Deserialize(textReader);
                }

(Where T is GetPointOfDelivery_Out and xml the example given above.)

Any help is welcome.

While looking somewhat deeper into stack overflow I found the answer in the following post:

https://stackoverflow.com/a/1232328/1145146

I added the XmlRoot attribute on the target class to be deserialized

[Serializable]
[XmlRoot("GetPointOfDelivery_Out", Namespace = "urn:webbeB2B:webservices:v0")]
[XmlType(AnonymousType = true, Namespace = "urn:webbeB2B:webservices:v0")]
public class GetPointOfDelivery_Out

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM