简体   繁体   中英

How do I deserialize XML in C# Envelope->Error

I need to deserialize a SOAP Error envelope

XML to deserialize:

<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP:Body>
        <faultcode>9001</faultcode>
        <faultstring>Some fault string</faultstring>
        <faultactor>Some fault factor</faultactor>
        <detail>Some Detail</detail>
    </SOAP:Body>
</SOAP:Envelope>

The Expected result is to deserialize the XML into the following classes but the values do not get deserialized I get NULL for all values

[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Body
{
    [XmlElement(ElementName = "faultcode")]
    public string Faultcode { get; set; }

    [XmlElement(ElementName = "faultstring")]
    public string Faultstring { get; set; }

    [XmlElement(ElementName = "faultactor")]
    public string Faultactor { get; set; }

    [XmlElement(ElementName = "detail")]
    public string Detail { get; set; }
}

[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
    [XmlElement(ElementName = "Body")]
    public Body Body { get; set; }

    [XmlAttribute(AttributeName = "SOAP", Namespace = "http://www.w3.org/2000/xmlns/")]
    public string SOAP { get; set; }
}

De-serialization code:

var serializer = new XmlSerializer(typeof(Envelope));

using (TextReader reader = new StringReader(xmlString))
{
    Envelope envelope = (Envelope)serializer.Deserialize(reader);
}

The namespace needs to be an empty string :

    [XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public class Body
    {
        [XmlElement(ElementName = "faultcode", Namespace = "")]
        public string Faultcode { get; set; }

        [XmlElement(ElementName = "faultstring", Namespace = "")]
        public string Faultstring { get; set; }

        [XmlElement(ElementName = "faultactor", Namespace = "")]
        public string Faultactor { get; set; }

        [XmlElement(ElementName = "detail", Namespace = "")]
        public string Detail { get; set; }
    }

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