对象数组的XML序列化

对象数组序列化不是什么难的东西,只是一直想弄懂XmlAttributeOverrides 的知识,于是想起了这个东东。以下对象数组

object[] objs = new object[] { 1, "2222", 33 };

XML序列化结果是

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfAnyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <anyType xsi:type="xsd:int">1</anyType>
  <anyType xsi:type="xsd:string">2222</anyType>
  <anyType xsi:type="xsd:int">33</anyType>
</ArrayOfAnyType>

使用以下方法序列化

Code

如果对象数组保存的是对象数组呢?有意思,为此,我试了以下数据,为了方便我使用了ArrayList,并尝试用上面的方法来序列化下面的array实例。

 

Code

结果出错了,我想是时候XmlAttributeOverrides 上场了,摆弄着XmlArrayItemAttribute、XmlRootAttribute还是被告知序列化ArrayList少了XmlRoot和XmlType。发现XmlSerializer的构造函数似乎可以指定这两个东东,于是一一查看各构造参数,似乎以下的更为简单实用

XmlSerializer(Type, array<Type>[]()[])
MSDN是这样说明第二个参数的:如果属性 (Property) 或字段返回一个数组,则 extraTypes 参数指定可插入到该数组的对象。

序列化的方法则作如下简单修改

Code

我的array被XML序列化的结果如下

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfAnyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <anyType xsi:type="ArrayOfAnyType">
    <anyType xsi:type="xsd:int">1</anyType>
    <anyType xsi:type="xsd:string">2222</anyType>
    <anyType xsi:type="xsd:int">33</anyType>
  </anyType>
  <anyType xsi:type="ArrayOfAnyType">
    <anyType xsi:type="xsd:int">2</anyType>
    <anyType xsi:type="xsd:string">kevin</anyType>
    <anyType xsi:type="xsd:int">35</anyType>
  </anyType>
</ArrayOfAnyType>

这串文字反序时可将ArrayList作为一般对象来反序列化就行了,不需要额外考虑什么。虽然节点看起来不大舒服,但能作为一般XML序列化结果来反序化为ArrayList,我觉得很好。

posted @ 2009-11-13 10:31  生命体验之kevin-Y  阅读(4396)  评论(1编辑  收藏  举报