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

时间:2016-12-21 15:54:28

标签: c# xml http xml-deserialization

我正在尝试编写一个序列化类,以便它可以反序列化来自摄像头设备的http响应,但是我会挂起来排除xsi:noNamespaceSchemaLocation标记。反序列化失败了" xsi"是未声明的前缀错误消息。

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#序列化类:

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的问题仍然存在。

2 个答案:

答案 0 :(得分:0)

xsi:noNamspaceSchemaLocation attritbute不应该像XML Document的结构一样反序列化。

由于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;}
        }
    }
}

答案 1 :(得分:0)

使用新的根元素包装此xml响应,其中定义了 xsi 命名空间:

<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>

您还需要更改类以添加Wrapper类 - 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 attritbute。