[英]Cannot Deserialize XmlArray with Namespace
I have the following XML: 我有以下XML:
<MovieRunTimes>
<ShowDate>6/9/2012</ShowDate>
<ShowTimesByDate xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:string>12:25</a:string>
<a:string>17:30</a:string>
<a:string>22:35</a:string>
</ShowTimesByDate>
<TicketURI>http://www.fandango.com/tms.asp?t=AANCC&m=112244&d=2012-06-09</TicketURI>
</MovieRunTimes>
And the following C# class: 以下是C#类:
public class MovieRunTimes
{
[XmlElement("ShowDate")]
public string ShowDate { get; set; }
[XmlElement("TicketURI")]
public string TicketUri { get; set; }
[XmlArray("ShowTimesByDate", Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
public List<string> ShowTimesByDate { get; set; }
}
Unfortunately the ShowTimesByDate is empty after I deserialize. 不幸的是,反序列化后ShowTimesByDate为空。 If I remove the namespace from the ShowTimesByDate element and the prefix from the string element, then it deserializes fine.
如果我从ShowTimesByDate元素中删除命名空间并从字符串元素中删除前缀,那么它反序列化很好。 How do I correctly use the namespace to deserialize the XML?
如何正确使用命名空间反序列化XML?
I discovered how to do this. 我发现了如何做到这一点。 If I amend the class to:
如果我将课程修改为:
public class MovieRunTimes
{
[XmlElement("ShowDate")]
public string ShowDate { get; set; }
[XmlElement("TicketURI")]
public string TicketUri { get; set; }
[XmlArray("ShowTimesByDate")]
[XmlArrayItem(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
public List<string> ShowTimesByDate { get; set; }
}
It deserializes correctly. 它正确地反序列化。
The trick is to add a namespace prefix ("a" in your case) to your Collection wrapper element: 诀窍是在Collection包装器元素中添加一个名称空间前缀(在您的情况下为“a”):
<MovieRunTimes >
<ShowDate>6/9/2012</ShowDate>
<a:ShowTimesByDate xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:string>12:25</a:string>
<a:string>17:30</a:string>
<a:string>22:35</a:string>
</a:ShowTimesByDate>
<TicketURI>http://www.fandango.com/tms.asp?t=AANCC&m=112244&d=2012-06-09</TicketURI>
</MovieRunTimes>
That is how it comes out after serializing with this code: 这是使用此代码序列化后的结果:
XmlSerializer xs = new XmlSerializer(typeof(MovieRunTimes));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("a", "http://schemas.microsoft.com/2003/10/Serialization/Arrays");
string result = null;
using(StringWriter writer = new StringWriter())
{
xs.Serialize(writer,mrt,ns);
result = writer.ToString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.