XmlSerializer - Deserialize different elements as collection of same element
I have the following XML part which schema I can't change. NUMBER, REGION, MENTION, FEDERAL are columns:
<COLUMNS LIST="20" PAGE="1" INDEX="reg_id">
<NUMBER WI开发者_开发百科DTH="3"/>
<REGION WIDTH="60"/>
<MENTION WIDTH="7"/>
<FEDERAL WIDTH="30"/>
</COLUMNS>
I want to deserialize it to public List<Column> Columns {get;set;}
property. So element name would go to Column.Name. Column class:
public class Column
{
//Name goes from Element Name
public string Name {get;set;}
[XmlAttribute("WIDTH")]
public int Width {get;set;}
}
Is it possible with XmlSerializer class?
You can use multiple XmlElements with one property:
[XmlElement("NUMBER")]
[XmlElement("REGION")]
[XmlElement("MENTION")]
[XmlElement("FEDERAL")]
public List<Column> Columns {get;set;}
It is even possible to specify different classes for different tag names:
[XmlElement(ElementName = "One", Type = typeof(OneItem))]
[XmlElement(ElementName = "Two", Type = typeof(TwoItem))]
public List<BaseItem> Items {get;set;}
If you are not allowed to change the schema, then the schema is more likely not to change. (If this is not a valid assumption, please let me know.) In that case, the use of XmlSerializer may well be overkill. Why not use Linq to XML?
class Program
{
static void Main(string[] args)
{
XDocument doc = XDocument.Load(@".\Resources\Sample.xml");
var columns = from column in doc.Descendants("COLUMNS").Descendants()
select new Column(column.Name.LocalName, int.Parse(column.Attribute("WIDTH").Value));
foreach (var column in columns)
Console.WriteLine(column.Name + " | " + column.Width);
}
class Column
{
public string Name { get; set; }
public int Width { get; set; }
public Column(string name, int width)
{
this.Name = name;
this.Width = width;
}
}
}
The snippit above loads your sample XML and then creates an enumeration of columns from it. Simple and effective. However, this requires .NET 3.0 or later, so if that is not an option for you then this is not the solution for you, unfortunately.
A link to Microsoft's Linq to XML documentation:
http://msdn.microsoft.com/en-us/library/bb387098.aspx
精彩评论