我很难从web服务解析soap响应并将其转换为c#对象。无论我做什么,它总是返回空元素。这是我的响应。
<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
}
这里是我的结果类
[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
借用 Linq to Xml 就足够了,就像下面的代码一样。
1-创建NameSpace。
XNamespace xn = "http://tempuri.org/";
2 - 将XDocument的查询改编为.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
希望对您有所帮助。