Lets consider a simple xml named as sample.xml. This can be an xml that you are getting as a output of webservice, a function or just a plain file that you might read in your application.
<users>
<user>
<id>1</id>
<name>asdf</name>
<fullname>asdf,asdf</fullname>
</user>
<user>
<id>2</id>
<name>qwer</name>
<fullname>qwer,qwer</fullname>
</user>
</users>
Lets create a XML Schema aka XSD file
Open ‘Visual Studio 2008 Command Prompt’ and type in
xsd sample.xml
This will generate sample.xsd file in the folder where you are currently running this command from. Below is how it looks.
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="users" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="users" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="user">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:string" minOccurs="0" />
<xs:element name="name" type="xs:string" minOccurs="0" />
<xs:element name="fullname" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
Lets create a class for serialization of xml file
xsd sample.xsd /classes /language:cs
This will generate sample.cs file. By default in the generated file, the collection used is Array.
private usersUser[] itemsField;
Lets use ObservableCollection as it is a generic dynamic data collection that provides notifications (using an interface "INotifyCollectionChanged") when items get added, removed, or when the whole collection is refreshed.
Below is how the modified class file looks like.
//——————————————————————————
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3607
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//——————————————————————————
using System.Xml.Serialization;
using System.Collections.ObjectModel;
//
// This source code was auto-generated by xsd, Version=2.0.50727.1432.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class users {
private ObservableCollection<usersUser> itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("user", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public ObservableCollection<usersUser> Items
{
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class usersUser {
private string idField;
private string nameField;
private string fullnameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string id {
get {
return this.idField;
}
set {
this.idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string fullname {
get {
return this.fullnameField;
}
set {
this.fullnameField = value;
}
}
}
Lets read a file from file system [ Serialization ]. Below is the sample code for doing so
System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
ofd.Multiselect = false;
ofd.Filter = "XML File|*.xml";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
if (File.Exists(ofd.FileName))
{
XmlSerializer deserializer = new XmlSerializer(typeof(users));
TextReader textReader = new StreamReader(ofd.FileName);
objUsers = new users();
objUsers = (users)deserializer.Deserialize(textReader);
textReader.Close();
}
}
catch
{
MessageBox.Show("Not a valid file");
}
}
To add a new user, below is the sample code
usersUser newuser = new usersUser();
newuser.id = "3";
newuser.name = "zxcv";
newuser.fullname = "zxcv,zxcv";
if (objUsers == null)
objUsers= new users();
objUsers.Items.Add(newuser);
Lets write a xml file from the objects that we have created [ Deserialization ]. Below is the sample code for doing so
if (objUsers == null)
objUsers = new users();
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "New";
dlg.DefaultExt = ".xml";
dlg.Filter = "XML file|*.xml";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filepath = dlg.FileName;
XmlSerializer serializer = new XmlSerializer(typeof(users));
TextWriter textWriter = new StreamWriter(filepath);
serializer.Serialize(textWriter, objUsers);
textWriter.Close();
}
Simple isn’t it
Sample code explained in this post is available here