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

标签 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 的问题依然存在。

最佳答案

只需用定义了 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>

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

关于c# - 使用 C# 反序列化 XML HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41266893/

相关文章:

c# - 通过反射加载 C# DLL,但应用 App.config

iphone - NSXMLParser:如何显示从 webservice 获得的响应?

java - 从 Spring Security 登录过程访问 HTTP Session

javascript - IE8 不显示图像(红色 x)...有时

http - Mule ESB 中的重新连接策略

c# - 在没有 Visual Studio 的情况下添加引用

c# - 如何从日期时间获取 AM/PM? C#

c# - 调用目标抛出异常 - 在 Visual Studio 中执行 .dtsx 文件时

php - 意外的 T_String 错误和 rss

java - 使用 SAX 解析器动态读取标签