|
Extensible Markup Language
The C# Column - Yashavant Kanetkar
Extensible
Markup Language is more popularly known by its acronym, XML. Unlike
HTML, which was designed to display data and to focus on how data
looks, XML has been designed to describe data and to focus on what
data is. XML is an open (non-proprietary) technology. What this
means is that the user is free to create any tags that are deemed
relevant and appropriate. XML is the universal language for describing
and exchanging data on the Web. First of all we will write a simple
XML script to get familiar with the terms used in XML.
<?xml version=1.0 encoding=utf-8
?>
<!simple XML example >->
<dirstructure>
<directory>Myfolder1</directory>
<textfile>f1.txt
<size>2</size>
</textfile>
<imagefile>img.jpg
<size>540</size>
</imagefile>
</dirstructure>
Here we have designed a structure of a
directory called Myfolder1. It can be used for passing
a directory structure across the Internet in an application that
allows users to share their folders across the Internet.
Every XML document begins with an optional
XML declaration containing version and encoding attributes, which
identify the document as the XML document. This declaration is known
as a Processing Instruction. All processing instructions
are wrapped in <? and ?>. Processing instructions are always
placed at the top of the document. The second statement enclosed
in <!and > is a comment. XML data is marked up
using tags enclosed in angled brackets (< >). In this document
the <directory>, <textfile>, <size>, <imagefile>
are tags. Tags are used in pairs called start tag and end tag. End
tag is marked with </>. Here </directory>, </textfile>,
etc, are end tags. Whatever is written between opening bracket and
closing bracket is called an element. The element name can consist
of alphabets, digits and underscores and should begin with an alphabet
or underscore. Every XML document contains a root element under
which all other elements are nested. In the above example, the elements
directory, textfile and imagefile are nested within the dirstructure
root element. The data written within the start and end tag is called
XML data.
Sometimes we might wish to add additional
information about an element. In such cases we need to add attributes
to our elements that define the properties of the element using
a name-value pair. For example, we can write attributes to the textfile
element as shown below.
<textfile description=contains names
of employees ext=.txt>f1.txt
<size>2</size>
</textfile>
Here, description and ext are called attributes
of the element textfile. An element can have any number of attributes.
In this article we would to see how to serialise objects using XML.
Serialisation of an object enables it to persist on the disk, which
can later be de-serialised by another application. We would use
the System.Xml.Serialization namespace for serialisation. When we
serialise an object, its fields and properties get stored as elements
or attributes. We can specify whether a field should be stored as
an element or attribute.
Create a Windows Application. Design the
form with two buttons, namely, serialize and show. On clicking the
Serialize button we would serialise an object of a class
named products. On clicking the Show button we would
de-serialise the object and display its values.
Firstly we would see how to serialise the
object. Here is the Serialize button handler.
private void serialize_Click ( object sender,
System.EventArgs e )
{
products p = new products( ) ;
p.Units = 100 ;
p.Price = 120.50f ;
p.Type = GEN ;
TextWriter w = new StreamWriter ( c:\\prod.xml ) ;
XmlSerializer sr = new XmlSerializer ( typeof ( products ) ) ;
sr.Serialize ( w, p ) ;
w.Close( ) ;
}
Here, firstly we have created an object of the
products class and initialised its fields using the public properties.
Next, we have created an object of the TextWriter class, which would
be used for character output to the specified file. The XmlSerializer
class is responsible for serialising the object of the specified
type. The Serialize( ) method of the XmlSerializer class serialises
the specified object and writes the XML document to file specified
by the text writer. This would generate the XML document as shown
below.
<?xml version=1.0 encoding=utf-8?>
<products xmlns:xsd=http://www.w3.org/2001/XMLSchema
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance>
<Units>100</Units>
<Price>120.5</Price>
<Type>GEN</Type>
</products>
Let us now de-serialise the object. For de-serialising
also we need the XmlSerializer object. De-serialisation is done
by calling the Deserialize( ) method of the XmlSerializer class.
private void show_Click ( object sender, System.EventArgs
e )
{
FileStream f = new FileStream ( C:\\prod.xml, FileMode.Open
) ;
XmlSerializer sr = new XmlSerializer ( typeof ( products ) ) ;
products p = ( products ) sr.Deserialize ( f ) ;
string s = string.Format ( Units: {0} Price: {1} Type: {2},
p.Units.ToString( ), p.Price.ToString( ), p.Type.ToString( ) ) ;
MessageBox.Show ( s ) ;
}
Now the only thing that remains is designing
the products class. Let us do that.
[ XmlRoot ( Namespace = , IsNullable
= false ) ]
public class products
{
[ XmlElement ( IsNullable = false ) ]
int units ;
[ XmlElement ]
float pr ;
[ XmlElement ]
string type ;
public int Units
{
get
{
return units ;
}
set
{
units = value ;
}
}
public float Price
{
get
{
return pr ;
}
set
{
pr = value ;
}
}
public string Type
{
get
{
return type ;
}
set
{
type = value ;
}
}
}
Serialisation of an object to the XML
document needs to annotate class and its members with attributes.
The XmlRoot attribute is given to create the root element. Writing
the attribute above class declaration would create a root element
of name products. As the name specifies, the XmlElement attribute
indicates that a public field or property represents an XML element.
Finally, add the following using statements.
using System.IO ;
using System.Xml.Serialization ;
Note that we can serialise only the public fields
and properties of public classes. XML serialisation does not convert
methods, indexers, private fields, or read-only properties. To serialise
all of an objects fields and properties, both public and private,
we will have to use the BinaryFormatter class instead of XML serialisation.
 |
Yashavant Kanetkar, one of the first
Express Computer columnists, is an established software expert,
speaker and author with several best-sellers to his credit,
including titles like “Let Us C” and the “Fundas” series. Contact
him at kanet@nagpur.dot.net.in |
|