我如何在C#Envelope-> Error中反序列化XML

时间:2019-07-16 01:31:36

标签: javascript c# .net xml soap

我需要反序列化SOAP错误信封

要反序列化的XML:

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

预期结果是将XML反序列化为以下类,但是值不会反序列化,所有值都会为NULL

[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; }
}

反序列化代码:

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

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

1 个答案:

答案 0 :(得分:1)

名称空间必须为空字符串:

    [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; }
    }