Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

c# - 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...