gpt4 book ai didi

c# - 如何忽略将 xml 反序列化为对象时的 soap 内容?

转载 作者:数据小太阳 更新时间:2023-10-29 01:47:42 24 4
gpt4 key购买 nike

当我得到一个 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());

香皂Body得到 <ns:INCLUIRCONHECIMENTOFRETESAIDA>以及我需要的所有信息。但是当我将它反序列化为 responseObj我将所有值都设为 null。

最佳答案

我没有足够的详细信息来为您填写 namespace 和元素名称,但使用 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.
}

关于c# - 如何忽略将 xml 反序列化为对象时的 soap 内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20478234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com