如何在C#对象中反序列化一种困难的XML格式并读取它以便使用其值?

问题描述

我有一个很难格式化的XML文档,我想阅读它并使用它的参数。

这是我要反序列化的 XML

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
      <APIResponse xmlns="https://testwebservice.com/">
          <Result>Api Result Message</Result>
      </APIResponse>
    </soap:Body>
</soap:Envelope>

我尝试了一些在其他问题中发现的代码示例

APIResponse envelopeClass = new APIResponse();
XmlSerializer serializer = new XmlSerializer(typeof(APIResponse),new XmlRootAttribute("Envelope"));
StringReader stringReader = new StringReader(xmlString);
envelopeClass = (APIResponse)serializer.Deserialize(stringReader);

但是到目前为止,没有任何帮助,因为我收到了这样的错误

system.invalidOperationException:'XML文档(1,42)中存在错误。'
内部异常
InvalidOperationException:预期

这些是我到目前为止在Visual Studio中使用选择性粘贴按钮使用的类。

[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true,Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.xmlsoap.org/soap/envelope/",IsNullable = false)]
public partial class Envelope
{
   public EnvelopeBody bodyField { get; set; }
}

[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true,Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
public partial class EnvelopeBody
{
   [System.Xml.Serialization.XmlElementAttribute(Namespace = "https://testwebservice.com/")]
   public  APIResponse aPIResponseField { get; set; }
}

[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true,Namespace="https://testwebservice.com/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="https://testwebservice.com/",IsNullable=false)]
public partial class APIResponse 
{
   public string resultField { get; set; }
}

尽管有所有这些,但我仍然不明白为什么会出现上述错误,我想指出的是,我还没有完全理解所有这些工作原理。 无论如何,如果有人可以帮助您,我将不胜感激。

请告诉我该XML格式文档应使用哪些正确的类以及如何反序列化它。

解决方法

您所称的“困难XML格式”实际上是标准SOAP(Simple Object Access Protocol)消息。 SOAP用作基于XML的Web服务的通信协议,首先要记住,您可以从获取XML内容的位置添加Web服务的服务引用。如果要从Web资源中获取此XML内容,请尝试将其添加为服务参考。

如果不是,并且您刚刚以某种方式结束了此XML内容,尽管有一些示例说明了如何通过解析XML和仅对其一部分进行序列化来从xml内部获取响应对象,这是我假定的是实现它的一种更精致,更安全的方法。

添加NuGet参考:Microsoft.Web.Services3

按如下所示更改类ApiResponse(将名称resultField更改为Result)

[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true,Namespace = "https://testwebservice.com/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "https://testwebservice.com/",IsNullable = false)]
public partial class APIResponse
{
    public string Result { get; set; }
}

然后使用SoapEnvelope类及其方法来获取ApiResponse对象:

using Microsoft.Web.Services3;

. . .
. . .

SoapEnvelope envelope = new SoapEnvelope();
envelope.LoadXml(xmlString);
APIResponse apiResponse = (APIResponse)envelope.GetBodyObject(typeof(APIResponse));

. . .
. . .