【发布时间】:2013-12-09 18:47:07
【问题描述】:
当我得到一个 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。
【问题讨论】:
-
使用
XDocument并执行document.Descendant("OCTE")? (或任何根名称应该是) -
后代,不确定我是否可以在 XmlDocument 类中找到此成员。
-
对,我把它和
XDocument混淆了。你可以改用那个类吗?不管怎样,我确信有一种方法可以将 XML 树向下导航到您的正文的值。 -
我可以使用,但是使用 Descendant 我得到一个 IENumerable 而不是一个 OCTE 对象
标签: c# xml xml-serialization