C# 用C反序列化XML HTTP响应#
我正在尝试编写一个序列化类,这样它就可以反序列化来自摄像头设备的http响应,但是我还是挂断了排除xsi:noNamespaceSchemaLocation标记的连接。反序列化失败,因为“xsi”是未声明的前缀错误消息 XML Http响应:C# 用C反序列化XML HTTP响应#,c#,xml,http,xml-deserialization,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='2016
<root xsi:noNamespaceSchemaLocation='http://www.example.com/vapix/http_cgi/recording/stop1.xsd'><stop recordingid='20161125_121817_831B_ACCC8E627419' result='OK'/></root>
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的问题仍然存在。属性不应反序列化,因为它是用于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>
无需反序列化NoNamespaceSchemaLocation属性。非常感谢,您的解决方案解决了这个问题。你能解释一下包装器实际上在做什么吗?包装器元素是新的根元素,它为整个文档定义了xsi名称空间(xmlns:xsi='),因此反序列化程序可以识别它,你可以使用这个名称空间的属性(xsi:noNamespaceSchemaLocation)。
<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>
[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; }
}