[英]XmlSerializer - Deserialize different elements as collection of same element
I have the following XML part which schema I can't change. 我有以下XML部分,无法更改其架构。 NUMBER, REGION, MENTION, FEDERAL are columns:
NUMBER,REGION,MENTION,FEDERAL是列:
<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. 我想将其反序列化为
public List<Column> Columns {get;set;}
属性。 So element name would go to Column.Name. 因此,元素名称将转到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? XmlSerializer类可以吗?
You can use multiple XmlElements with one property: 您可以将多个XmlElement与一个属性一起使用:
[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.
(如果这不是一个有效的假设,请让我知道。)在这种情况下,使用XmlSerializer可能会过大。 Why not use Linq to XML?
为什么不使用Linq到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. 上面的代码段将加载示例XML,然后从中创建一个列枚举。 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.
但是,这需要.NET 3.0或更高版本,因此,不幸的是,如果这不是您的选择,那么这不是您的解决方案。
A link to Microsoft's Linq to XML documentation: 到Microsoft的Linq to XML文档的链接:
http://msdn.microsoft.com/en-us/library/bb387098.aspx http://msdn.microsoft.com/en-us/library/bb387098.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.