While the XML serializer will automatically use proper names for XML tags that products based on the names chosen for variables at design time, there are times when you have to adjust the output, perhaps to match a pre schema -existing or summarize the data storage format somewhat from the inner workings of your application. To accomplish this, the serialization process is controlled by a number of attributes in the System.Xml.Serialization namespace, which is well documented in the contents of the MSDN Library with Visual Studio.NET. (If you're confused about the concept of an attribute that is unique to the frame. NET may refer to work in C # reference or MSDN Library before continuing. ) Andrew Ma previous tutorial covered many of the basics, such as [XmlElement ( "name")], which states that a member of the class immediately after the attribute is represented as an element with the tag name indicated in the element, [XmlAttribute ( "name")], which states that the following class member will be represented as an attribute of its parent element, and [XmlRoot ( "name")], which defines the name of the XML document root element .
First we'll start with a code sample of our class which we will serialize and then go on to explain what it does:
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
// Shopping list class which will be serialized
[XmlRoot("shoppingList")]
public class ShoppingList {
private ArrayList listShopping;
public ShoppingList() {
listShopping = new ArrayList();
}
[XmlElement("item")]
public Item[] Items {
get {
Item[] items = new Item[ listShopping.Count ];
listShopping.CopyTo( items );
return items;
}
set {
if( value == null ) return;
Item[] items = (Item[])value;
listShopping.Clear();
foreach( Item item in items )
listShopping.Add( item );
}
}
public int AddItem( Item item ) {
return listShopping.Add( item );
}
}
// Items in the shopping list
public class Item {
[XmlAttribute("name")] public string name;
[XmlAttribute("price")] public double price;
public Item() {
}
public Item( string Name, string Price ) {
name = Name;
price = Price;
}
}
0 comments:
Post a Comment