Library code snippets
Serialize and deserialize objects to an XML file
This code shows the simplest way to automatically convert the information in an object to an XML file and back into an object. This is useful if you need to make information available web-server like on your server for other applications to pick it up. I just cut the significant parts out of Visual Studio so you'll have to build it into whatever form you like. Make sure you have write permissions on the directory.
from the .aspx file
//serialize
private void Button3_Click(object sender, System.EventArgs e)
{
Book b = new Book();
b.Title = "Windows Forms";
b.Isbn = "728372837";
XmlSerializer serializer = new XmlSerializer(typeof(Book));
TextWriter tw = new StreamWriter(Server.MapPath("book1.xml"));
serializer.Serialize(tw,b);
tw.Close();
}
//deserialize
private void Button4_Click(object sender, System.EventArgs e)
{
XmlSerializer serializer = new XmlSerializer(typeof(Book));
TextReader tr = new StreamReader(Server.MapPath("book1.xml"));
Book b = (Book)serializer.Deserialize(tr);
tr.Close();
Title.Text = b.Title;
Isbn.Text = b.Isbn;
}
Book.cs
using System;
namespace Serialize
{
public class Book
{
public string Title;
public string Isbn;
}
}
Related articles
Related discussion
-
Help required to know about sync of RFID read tag thru Handheld-sample code in .net
by usha@myrf (0 replies)
-
How to query multiple xml files?
by lamin (0 replies)
-
Tree structures in ASP.NET and SQL Server
by satport (28 replies)
-
Problem in uploading the image using fck editor in asp.net 2.0
by quynt (12 replies)
-
handling special character in xslt's
by bussureddy82 (1 replies)
Related podcasts
-
The One With The Maracas ...
Its the last day of the MVP Summit, the boys dive deep into XML and dynamic language sessions all NDA unfortunately so don't expect them to say anything ... But an interview with Russ Nemhauser uncovers his love for the Mac and concern with some project management methodologies. Brad Abrams gets ...
Events coming up
-
Mar
15
DevWeek 2010
London, United Kingdom
DevWeek is Europe’s leading independent conference for software developers, database professionals and IT architects, and features expert speakers on a wide range of topics, including .NET 4.0, Silverlight 3, WCF 4, Visual Studio 2010, REST, Windows Workflow 4, Thread Synchronization, ASP.NET 4.0, SQL Server 2008 R2, LINQ, Unit Testing, CLR & C# 4.0, .NET Patterns, WPF 4, F#, Windows Azure, ADO.NET, Entity Framework, Debugging, T-SQL Tips & Tricks, and more.
Comments
Leave a comment
Sign in or Join us (it's free).