Mark Wilson I am the creator of TopXML. I am available for international and local (Australia) contracts. I am a Solution Architect/Business Analyst. I have worked in IT in several countries (NZ, Australia, South Africa, UK) building and training teams for government and very large non-governmental organizations. I am ex-Microsoft Consulting Services. I wrote the first book on Microsoft XML published in 2000 called XML Programming with VB and ASP. Most recently I have been building tools for the SEO industry. Ask me for a 37 point SEO health-checkup for your website.
First posted :
03/24/2008
Times viewed :
573
Metadata Attributes
A complete discussion of Metadata Attributes is beyond the scope here. Nevertheless we need to understand the concepts behind metadata attributes
to understand how XML serialization works. When we talk about attributes in this
section, we will always refer to metadata attributes, not XML attributes.
Attributes are a programming concept first introduced to the Microsoft
platform with Microsoft Transaction Sever, which later became COM+. Attributes
are annotations to an interface or a class definition to specify certain
behavior. For example, no explicit coding was necessary to modify the
transactional behavior of a class, it was declared by the presence of a
transaction attribute. This is why the concept is also referred to as
declarative programming.
The .NET platform takes attributes much further and uses them in a variety of
places. Assemblies, classes, fields and methods, each can have attributes. Some
are used by the compiler, some are used by the runtime, e.g. to identify a
method requires a call to a web service, or how to serialize a class to XML.
There is very little overhead associated when using attributes.
Attaching attributes to a class is done directly in the source code. The
syntax to initialize a metadata attribute and attach it to a class or a method
in C# is either:
This chapter uses the second variation where possible because it is more
descriptive and easier to understand.
XmlRootAttribute
Now what does all this have to do with XML or serialization? A whole lot! The
System.Xml.Serialization namespace introduces a set of attributes to control how
classes are mapped to XML. Let’s look at a quick example: One of the
attributes used with XML serialization is the XmlRootAttribute to change the
name of the root element of a serialization hierarchy. You would add the
XmlRootAttribute to a class like this:
using System.Xml.Serialization;
[XmlRootAttribute(Name="Car", IsNullable=false)]
public class Automobile
{
// class implementation goes here
}
This is as far as we’ll go introducing attributes. You now know enough
about attributes to use them for serialization. If you are interested to learn
more about using attributes throughout the .NET platform you can find some
references to more in depth discussions in the further reading section.