XmlSerializer - 将不同元素反序列化为相同元素的集合
我有以下 XML 部分,我无法更改该部分的架构。 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>
我想将其反序列化为 public List
属性。因此元素名称将转到 Column.Name。列类:
public class Column
{
//Name goes from Element Name
public string Name {get;set;}
[XmlAttribute("WIDTH")]
public int Width {get;set;}
}
是否可以使用 XmlSerializer 类?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用具有一个属性的多个 XmlElement:
甚至可以为不同的标记名称指定不同的类:
You can use multiple XmlElements with one property:
It is even possible to specify different classes for different tag names:
如果不允许您更改架构,则架构很可能不会更改。 (如果这不是一个有效的假设,请告诉我。)在这种情况下,使用 XmlSerializer 可能就有点矫枉过正了。为什么不使用 Linq to XML?
上面的代码片段加载示例 XML,然后从中创建列的枚举。简单有效。但是,这需要 .NET 3.0 或更高版本,因此,如果这不适合您,那么不幸的是,这不是您的解决方案。
Microsoft 的 Linq to XML 文档的链接:
http://msdn.microsoft.com /en-us/library/bb387098.aspx
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?
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