XmlSerializer - Deserialize different elements as collection of same element

牧云@^-^@ 提交于 2019-11-28 13:03:08

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

Konstantin Vdovkin

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;}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!