Search:
Locator+ Code:
FTPOnline Channels Conferences Resources Hot Topics Partner Sites Magazines About FTP RSS 2.0 Feed

Back to VSLive! Show Daily Home


Map CLR Objects To XML Docs
With the System.Xml.Serialization library, you can custom-map XSD types to CLR types.
by Aaron Skonnard

VSLive! SF, Day 2, February 13, 2002 — XML has its own type system based on XML Schema (XSD). The CLR type system is not based on XML Schema. The System.Xml.Serialization library allows XSD types to be mapped to CLR types in a relatively customizable way. This code fragment illustrates how to map a CLR object to an XML document:

using System.IO;
using System.Xml;
using System.Xml.Serialization

static void WriteObjectToFile(Object obj, string 
   filename) {
  Stream writer = new FileStream(filename, 
     FileMode.Create);
  try {
    XmlSerializer ser = new 
        XmlSerializer(obj.GetType());
    ser.Serialize(writer, obj);
  }
  finally {
    writer.Close();
  }
}

And the reverse is also true. This code fragment illustrates how to map an XML document back into a CLR object:

using System.Stream;
using System.Xml;
using System.Xml.Serialization

static object ReadObjectFromFile(Type type, 
    string filename) {
  Object result = null;
  Stream reader = new FileStream(filename, 
    FileMode.Open);
  try {
    XmlSerializer ser = new XmlSerializer(type);
    result = ser.Deserialize(reader);
  }
  finally {
    reader.Close();
  }
  return result;
}

About the Author
Aaron Skonnard is a consultant, instructor, and author specializing in Windows technologies and Web applications. Aaron teaches courses for DevelopMentor, is a columnist for Microsoft Internet Developer, the author of Essential WinInet, and co-author of Essential XML: Beyond MarkUp (Addison Wesley Longman). Contact him at http://staff.develop.com/aarons.

Back to top





Java Pro | .NET Magazine | Visual Studio Magazine | XML & Web Services Magazine
VSLive! | Thunder Lizard Events | Discussions | Newsletters | FTP Home