使用 C# 反序列化 XML HTTP 响应

Deserialize XML HTTP Response with C#

我正在尝试编写一个序列化 class,以便它可以反序列化来自相机设备的 http 响应,但是我在排除 xsi:noNamespaceSchemaLocation 标记时挂断了电话。反序列化失败,"xsi" is an undeclared prefix error message.

XML Http 响应:

<root xsi:noNamespaceSchemaLocation='http://www.example.com/vapix/http_cgi/recording/stop1.xsd'><stop recordingid='20161125_121817_831B_ACCC8E627419' result='OK'/></root>

C#代码:

try
{
  StopRecord ListOfStops = null;
  XmlSerializer deserializer = new XmlSerializer(typeof(StopRecord));
  using (XmlTextReader reader = new XmlTextReader(new StringReader(httpResponse)))
  {
   ListOfStops = deserializer.Deserialize(reader) as StopRecord ;
  }
}
catch (Exception ex)
{
   Console.WriteLine(ex.InnerException);
}

C# 序列化 Class:

public class StopRecord
{
   [Serializable()]
   [System.Xml.Serialization.XmlRoot("root")]
   public class Root
   {
     public class stop
     {
       public stop(){}
       [System.Xml.Serialization.XmlAttribute("recordingid")]
       public string recordingid {get;set;}

       [System.Xml.Serialization.XmlAttribute("result")]
       public string result {get;set;}
     }
   }
}

更新:将 XmlElements 更改为 XmlAttributes。 xsi的问题依然存在

不应反序列化 xsi:noNamspaceSchemaLocation 属性,因为它是针对 XML 文档的结构。

由于recordingid和result是属性,不是元素,所以需要序列化为XmlAttribute,而不是XmlElement。

public class StopRecord
{
    [Serializable()]
    [System.Xml.Serialization.XmlRoot("root")]
    public class Root
    {
        public class stop
        {
            public stop(){}

            [System.Xml.Serialization.XmlAttribute("recordingid")]
            public string recordingid {get;set;}

            [System.Xml.Serialization.XmlAttribute("result")]
            public string result {get;set;}
        }
    }
}

只需用定义 xsi 命名空间的新根元素包装此 xml 响应:

<wrapper xmlns:xsi='http://www.example.com'>
    <!-- original response goes here -->
    <root xsi:noNamespaceSchemaLocation='http://www.example.com/vapix/http_cgi/recording/stop1.xsd'>
        <stop recordingid='20161125_121817_831B_ACCC8E627419' result='OK'/>
    </root>
</wrapper>

您还需要更改 classes 以添加包装器 class - working example on .NET Fiddle:

[Serializable]
[XmlRoot("wrapper")]
public class StopRecord
{
    [XmlElement("root")]
    public Root Root { get; set; }
}

public class Root
{
    [XmlElement("stop")]
    public Stop stop { get; set; }
}

public class Stop
{
    [XmlAttribute("recordingid")]
    public string recordingid { get; set; }

    [XmlAttribute("result")]
    public string result { get; set; }
}

不需要反序列化noNamspaceSchemaLocation属性。