当我获得xml时,我需要将其反序列化为特定对象,并通过Web服务方法中的参数传递它。
代码:
var document = new XmlDocument();
document.Load(@"C:\Desktop\CteWebservice.xml");
var serializer = new XmlSerializer(typeof(OCTE));
var octe = (OCTE) serializer.Deserialize(new StringReader(document.OuterXml));
serviceClient.InsertOCTE(octe);
但是当我尝试反序列化时,我收到错误说
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" > was not expected.
我需要忽略信封标签和其他SOAP内容。 我怎么能这样做?
xml文件:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns="http://192.168.1.180:8085/">
<soapenv:Header/>
<soapenv:Body>
<ns:INCLUIRCONHECIMENTOFRETESAIDA>
<ns:CONHECIMENTOFRETE>
<ns:CSTICMS></ns:CSTICMS>
</ns:CONHECIMENTOFRETE>
</ns:INCLUIRCONHECIMENTOFRETESAIDA>
<soapenv:Body>
测试代码:
XNamespace soap = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace m = "http://192.168.1.180:8085/";
var soapBody = xdoc.Descendants(soap + "Body").First().FirstNode;
var serializer = new XmlSerializer(typeof(OCTE));
var responseObj = (OCTE)serializer.Deserialize(soapBody.CreateReader());
soap Body
获取<ns:INCLUIRCONHECIMENTOFRETESAIDA>
包含我需要的所有信息。但是当我将其反序列化为responseObj
时,我将所有值都设为null。
答案 0 :(得分:7)
我没有足够的详细信息为您填写命名空间和元素名称,但使用W3C's example SOAP response,以下代码和类反序列化对象:
var xdoc = XDocument.Load(@"C:\Desktop\CteWebservice.xml");
XNamespace soap = "http://www.w3.org/2001/12/soap-envelope";
XNamespace m = "http://www.example.org/stock";
var responseXml = xdoc.Element(soap + "Envelope").Element(soap + "Body")
.Element(m + "GetStockPriceResponse");
var serializer = new XmlSerializer(typeof(GetStockPriceResponse));
var responseObj =
(GetStockPriceResponse)serializer.Deserialize(responseXml.CreateReader());
[XmlRoot("GetStockPriceResponse", Namespace="http://www.example.org/stock")]
public class GetStockPriceResponse
{
public decimal Price { get; set; }
}
您可以对OCTE
课程执行相同操作。
[XmlRoot("INCLUIRCONHECIMENTOFRETESAIDA",Namespace="http://192.168.1.180:8085/")]
public class OCTE
{
// with property mapping to CONHECIMENTOFRETE, etc.
}
答案 1 :(得分:1)