我有以下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>
以下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; }
}
不幸的是,反序列化后ShowTimesByDate为空。如果我从ShowTimesByDate元素中删除命名空间并从字符串元素中删除前缀,那么它反序列化很好。如何正确使用命名空间反序列化XML?
答案 0 :(得分:3)
我发现了如何做到这一点。如果我将课程修改为:
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; }
}
正确反序列化。
答案 1 :(得分:1)
诀窍是在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>
这是用这段代码序列化后的结果:
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();
}