sir*_*val 2 c# xml serialization
假设我有这个虚构的xml:
<Schedule>
<Month name="March">
<Day name="Monday" />
</Month>
<Month name="April">
<Day name="Tuesday" />
<Day name="Monday" />
</Month>
</Schedule>
Run Code Online (Sandbox Code Playgroud)
I want to deserialize the above. However I want to deserialize this xml using a different class hierarchy because the classes Schedule, Month and Day are used somewhere else.
So for example I want to have these classes:
[XmlRoot( "Schedule" )
public class ParserSchedule
{
[XmlElement("Month")]
public List<ParserMonth> Month{ get; set; }
}
public class ParserMonth
{
[XmlAttribute( "name" )]
public string Name{ get; set; }
[XmlElement("Day")]
public List<ParserDay> Day{ get; set; }
}
public class ParserDay
{
[XmlAttribute( "name" )]
public string Name{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)
However this doesn't work. I get exceptions saying Day cannot be serialized because it does not have a default public constructor. And I guess this happens because it tries to create an instance of the Day class and not the ParserDay class..
Anyway to do this?
This is working perfectly fine for me. You must have some other problem or didn't paste your code correctly/completely.
void Main()
{
var ser = new XmlSerializer(typeof(ParserSchedule));
var xml = @"<Schedule>
<Month name=""March"">
<Day name=""Monday"" />
</Month>
<Month name=""April"">
<Day name=""Tuesday"" />
<Day name=""Monday"" />
</Month>
</Schedule>";
using (var reader = new StringReader(xml))
{
var schedule = (ParserSchedule)ser.Deserialize(reader);
schedule.Dump(); // LINQPad method to dump object to debug
}
}
[XmlRoot("Schedule")]
public class ParserSchedule
{
[XmlElement("Month")]
public List<ParserMonth> Month{ get; set; }
}
public class ParserMonth
{
[XmlAttribute("name")]
public string Name{ get; set; }
[XmlElement("Day")]
public List<ParserDay> Day{ get; set; }
}
public class ParserDay
{
[XmlAttribute( "name" )]
public string Name{ get; set; }
}
public class Day
{
private Day() {} // new Day() should fail to compile
}
Run Code Online (Sandbox Code Playgroud)
Coding style note: You really should call your members that return collection type as plural public List<ParserDay> Days{ get; set; } to avoid confusion.
| 归档时间: |
|
| 查看次数: |
5272 次 |
| 最近记录: |