小新的技术天地

Make It Works !

博客园 首页 新随笔 联系 订阅 管理
假设我们需要XML,但是不想要SOAP特有的额外信息,应该怎么办?我们可以使用类库XMLSerializer。
代码如下:
using System;
using System.IO;
using System.Xml.Serialization;

//[Serializable]
public class Insect
{
    
public string name;
    
    
//[NonSerialized]
    [XmlIgnore]public int id;
    
    
public Insect(string name, int id)
    
{
        
this.name = name;
        
this.id= id;
    }

    
public override string ToString()
    
{
        
return String.Format("{0}:{1}", name, id);
    }

    
    
public Insect() {}
}


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

}

注意:
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>
posted on 2004-10-22 19:14  小新0574  阅读(2023)  评论(0编辑  收藏  举报