我正在尝试编写一个序列化类,这样它将反序列化来自照相机设备的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的问题仍然存在。
发布于 2016-12-21 17:44:30
只需使用定义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>您还需要更改类以添加包装类- .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吸引器。
发布于 2016-12-21 17:22:10
不应该像对XML的结构那样反序列化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;}
}
}
}https://stackoverflow.com/questions/41266893
复制相似问题