Soap 对 C# class 的响应总是 return 空值

Soap response to C# class always return null values

我很难解析来自 Web 服务的 soap 响应并将其转换为 C# 对象。无论我做什么,它总是 returns 空元素。 这是我的回应。

<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' 
 xmlns:tem='http://tempuri.org/'>
 <soapenv:Header/> <soapenv:Body>
 <tem:Response><tem:Result>
  <RETN>108</RETN><DESC> This is an error</DESC></tem:Result></tem:Response>
   </soapenv:Body>
 </soapenv:Envelope>

这就是我解析此响应的方式。

var xDoc = XDocument.Parse(response);
var xLoginResult = xDoc.Root.Descendants().FirstOrDefault(d => d.Name.LocalName.Equals("Result"));
var serializer = new XmlSerializer(typeof(Result));
using (var reader = xLoginResult.CreateReader())
{
    var convertedResonse= (Result)serializer.Deserialize(reader);
    // inside this convertedResonse RETN and  DESC is alway null
}

这是我的结果Class

   [XmlRoot(ElementName = "Result", Namespace = "http://tempuri.org/")]
    public class Result
    {
        [XmlElement("RETN")]
        public string RETN { get; set; }
        [XmlElement("DESC")]
        public string DESC { get; set; }
    }

    [XmlRoot(ElementName = "Response", Namespace = "http://tempuri.org/")]
    public class Response
    {
        [XmlElement(ElementName = "Result", Namespace = "http://tempuri.org/")]
        public Result Result { get; set; }
    }

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

    [XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public class Envelope
    {
        [XmlElement(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
        public string Header { get; set; }
        [XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
        public Body Body { get; set; }
        [XmlAttribute(AttributeName = "soapenv", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Soapenv { get; set; }
        [XmlAttribute(AttributeName = "tem", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Tem { get; set; }
    }

convertedResonse 中的值始终为空。 任何想法将不胜感激?

问题中贴出的Xml不需要使用XmlSerializer,只需使用[=XDocument即可26=]Linq to Xml 就足够了,就像下面的代码:

1 - 创建命名空间:

XNamespace xn = "http://tempuri.org/";

2 - 将 XDocument 的查询调整为:

Result result = xDoc
    .Descendants(xn + "Result")
    .Select(x => new Result { DESC = x.Element("DESC").Value, RETN = x.Element("RETN").Value })
    .FirstOrDefault();

Console.WriteLine($"DESC:{result.DESC}, RETN:{result.RETN}");

结果

DESC: This is an error, RETN:108

希望对您有所帮助。