序列化 - 使用XmlSerializer进行序列化

假设我们需要XML,但是不想要SOAP特有的额外信息,应该怎么办?我们可以使用类库XMLSerializer。
代码如下:
None.gif using  System;
None.gif
using  System.IO;
None.gif
using  System.Xml.Serialization;
None.gif
None.gif
// [Serializable]
None.gif
public   class  Insect
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public string name;
InBlock.gif    
InBlock.gif    
//[NonSerialized]
InBlock.gif
    [XmlIgnore]public int id;
InBlock.gif    
InBlock.gif    
public Insect(string name, int id)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
this.name = name;
InBlock.gif        
this.id= id;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
public override string ToString()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
return String.Format("{0}:{1}", name, id);
ExpandedSubBlockEnd.gif    }

InBlock.gif    
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public Insect() dot.gif{}
ExpandedBlockEnd.gif}

None.gif
None.gif
class  SerializeRawXMLApp
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    [STAThread]
InBlock.gif    
static void  Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        Insect i 
= new Insect("Meadow Brown"12);
InBlock.gif        XmlSerializer x 
= new XmlSerializer(typeof(Insect));
InBlock.gif        Stream s 
= File.Create("AnInsect.xml");
InBlock.gif        
InBlock.gif        x.Serialize(s, i);
InBlock.gif        s.Seek(
0, SeekOrigin.Begin);
InBlock.gif        Insect j 
= (Insect)x.Deserialize(s);
InBlock.gif        s.Close();
InBlock.gif        Console.WriteLine(j);
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

注意:
1.这里去掉了Serializable属性和NonSerilizable属性,使用XMLIgnore属性完成NonSerialized类似的功能。
2.XmlSerializer不能安全的访地问私有成员,所以我们改为共有成员,也可以提供合适的公有属性(Property)。
3.Xml要求我们的类有一个默认构造器,这个条件可能已经满足了。
我们可以用VS.NET打开AnInsect.xml文件,可以看到以下信息:
<?xml version="1.0"?>
<Insect xmlns:xsd=" http://www.w3.org/2001/XMLSchema" xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance">
  <name>Meadow Brown</name>
</Insect>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值