声明:如非注明原创,则本blog所发日志为引用,向原创作者致意!敬礼!
佛曰: 人生最大的财富是健康
佛曰: 人生最大的幸福是放得下
站点公告
最新日志
博文评论
博客留言
博客登陆
博文搜索
博客信息
收藏连接
 
xmlserializer(转)
janedong 发表于 2006/6/5 15:52:00
Object serialization is an important topic which is quite powerful if used correctly. Serialization allows programms to persist objects by storing then in files. In the case of this tutorial, into XML files. XML has become the standard for storage in the recent years and its good to see that with XML serialization built into the .NET framework, it will be very simple to build applications which can interop well with any other software, Microsoft or not.
This tutorial assumes a basic knowledge of programming. One thing that people may not be familiar with is the concept of attributes which is used heavily in this tutorial.

XML Serialization Attributes
First we'll start with a code sample of our class which we will serialize and then go on to explain what it does:
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

// Shopping list class which will be serialized
[XmlRoot("shoppingList")]
public class ShoppingList {
  private ArrayList listShopping;

  public ShoppingList() {
    listShopping = new ArrayList();
  }

  [XmlElement("item")]
  public Item[] Items {
    get {
      Item[] items = new Item[ listShopping.Count ];
      listShopping.CopyTo( items );
      return items;
    }
    set {
      if( value == null ) return;
      Item[] items = (Item[])value;
      listShopping.Clear();
      foreach( Item item in items )
        listShopping.Add( item );
    }
  }

  public int AddItem( Item item ) {
    return listShopping.Add( item );
  }
}

// Items in the shopping list
public class Item {
  [XmlAttribute("name")] public string name;
  [XmlAttribute("price")] public double price;

  public Item() {
  }

  public Item( string Name, string Price ) {
    name = Name;
    price = Price;
  }
}

On first glance, this class appears to be a normal class without anything out of the ordinary in the code, but when we look at the method signatures, we see that there are attributes around it such as [XmlRoot], [XmlElement] and [XmlAttribute]These are necessary for any class that will be serialized. This is the magic which allows us to specify how the class will be serialized and what will be elements or attributes and how everything will be named.
Some other useful attributes are:
[XmlIgnore] - this will cause the serializer to ignore the property during serialization. This will exclude it from the XML.

Serialzation
Now here's the cool part. This is how serialization works:
ShoppingList myList = new ShoppingList();
myList.AddItem( new Item( "eggs",1.49 ) );
myList.AddItem( new Item( "ground beef",3.69 ) );
myList.AddItem( new Item( "bread",0.89 ) );

// Serialization
XmlSerializer s = new XmlSerializer( typeof( ShoppingList ) );
TextWriter w = new StreamWriter( @"c:\list.xml" );
s.Serialize( w, myList );
w.Close();

// Deserialization
ShoppingList newList;
TextReader r = new StreamReader( "list.xml" );
newList = (ShoppingList)s.Deserialize( r );
r.Close();

The first chunk of code is simply creating an instance of the ShoppingList class and populating it. After that, we have the serialization part. Here is where the object gets converted into XML. As you can see, all it requires is the use of the XmlSerializer class which is set to serialize anything of type ShoppingList (look at the constructor). The serializer does its work when the Serialize method is called and will output XML to any stream. In this case, we have it output to a file.
Next there is the deserialization part. Here we use the same serializer (since it's set to the right type) and we read in an XML file and the Deserialize method will create the appropriate ShoppingList class object. This code sample shows serialization from a file, but you could just as easily do it from an http stream.

xsd.exe
Now I want to highlight the a useful utility. xsd.exe is a utility to generate schema or class files from given source. It is included with the .NET Framework. There are three main uses for xsd.exe.

First, xsd.exe <schema>.xsd which will create source code for the appropriate class to de-serialize your object.

Second, xsd.exe <assembly>.dll|.exe is used to read the code and generate a schema (.xsd) file for you.

Finally, xsd.exe <instance>.xml|.xdr which will try to infer an .xsd file which you can then use to create an appropriate class.

From a command prompt, type: "xsd.exe" to get more help information.

Conclusion
So there you have it. XML Serialization in C#. This is an incredibly useful way for application developers to persist objects by storing them in a file. It makes it really simple for any programmer to save configuration settings into XML files or application documents as well.

Tips:
- only typed arrays can be serialized and deserialized. If you have any collections such as an ArrayList, you will have to convert it an array.

Return to Browsing Tutorials

Email this Tutorial to a Friend

Rate this Content:  
low quality  1 2 3 4 5  high quality

Reader's Comments Post a Comment
 
Another very useful attribute I forgot to mention is the [XmlText] attribute. It will cause the field to become the text between an xml element.
-- Andrew Ma, September 25, 2002
 
Very nice... I've been storing application setting in xml files (and the system registry) lately, but I've been doing it the hard way! Thanks for enlightening me!
-- Philip Lanier, September 25, 2002
 
For application setting, you should storing your things in the .config file (ie. if you app is called myapplication.exe, the config file is called myapplication.exe.config).
This way, you don't even need to do the serialization and deserialization. You can just get your settings using ConfigurationSettings.AppSettings["keyname"]. You can find more about it in the MSDN docs. It's pretty simple and straightforward.
-- Andrew Ma, September 25, 2002
 
That's really cool. It will save me tons of time and headaches, thanks.
-- Brent Bishop, September 27, 2002
 
And one should never be storing their application settings in the registry with .NET applications: let the past go, man! :-)
-- Heath Stewart, September 29, 2002
 
Great syntax very helpful, saves me time from figuring it out.
-- Sean Fitzgerald, October 01, 2002
 
Good example, but there's a small error in the Item class definition:

public class Item {
[XmlAttribute("name")] public string name;
[XmlAttribute("price")] public double price;
...
public Item( string Name, string Price ) {

should be

public Item( string Name, double Price ) {


No big deal, but thought it was worth bringing up if anyone wanted to try the code through copy and paste...
-- Ben Andrews, October 04, 2002
 
Thanks Andrew, exactly what I was looking for.
-- Luke Walker, April 19, 2003
 
I think that the tip section in the article might be partially wrong. I have ArrayList which is automatically serialized. Though I have to define the element type.

[XmlElement("party", typeof(Party))]
public ArrayList parties = new ArrayList();

-- N S, July 03, 2003
 
i know its not related w this subject, but happened when trying to run this example. when executing the line:

TextWriter w = new StreamWriter( @"c:\\list.xml" );

i get an exception:

An unhandled exception of type 'System.Security.SecurityException' occurred in mscorlib.dll

Additional information: Request for the permission of type System.Security.Permissions.FileIOPermission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed.

what is nonsense to me, since ASPNET user have full access to C:\...
-- Daniel Marreco, August 01, 2003
 
Very nice information..

Daniel.. as for your problem, I'm not exactly sure what the problem is, but I noticed this.. @"c:\\list.xml"

the @ sign means that the text is literal and doesn't have to be escaped.

which means you can use @"C:\list.xml" and it should work fine. If you want to do it the old way with "c:\\list.xml" then leave off the @ sign.
-- Drakier Dominaeus, August 27, 2003
 

发表评论:

    昵称:
    密码:
    主页:
    标题: