XmlSerializer - Deserialize different elements as collection of same element

梦想的初衷 提交于 2019-11-27 19:28:25

问题


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 WIDTH="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?


回答1:


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




回答2:


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;}


来源:https://stackoverflow.com/questions/2874680/xmlserializer-deserialize-different-elements-as-collection-of-same-element

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