XML namespaces are contained by instances of XmlSerializerNamespaces class. To create fully qualified names in an XML document:
- Create an instance of XmlSerializerNamespaces class and add the required (prefix, namespace) pairs.
- Apply the appropriate XML serialization attributes and at the same time setting the Namespace property of each such attribute to one of the namespaces specified in step 1.
- Pass the XmlSerializerNamespaces instance to XmlSerializer.Serialize() method.
The following example illustrates:
namespace XMLNamespaceSerialization
{
public class Price
{
// Serialize the currency field as an attribute with the given namspace
[XmlAttribute( Namespace ="www.diranieh.com")]
public string currency;
// Serialize the price field as an attribute with the given namspace
[XmlAttribute( Namespace ="www.diranieh.com")]
public decimal price;
}
public class Book
{
// Serialize the title field as an element with the given namspace
[XmlElement( Namespace = "www.diranieh.com") ]
public string Title;
// Serialize the price field as an element with the given namspace
[XmlElement( Namespace = "www.diranieh.com") ]
public Price price;
}
public class Books
{
// Serilize the alBooks filed with the given namespace
[XmlElement(typeof(Book), Namespace = "www.diranieh.com")]
public ArrayList alBooks = new ArrayList();
}
}
private void btnNamespaces_Click(object sender, System.EventArgs e)
{
/* Create a collection of books */
// Book1
XMLNamespaceSerialization.Book book1 = new XMLNamespaceSerialization.Book();
XMLNamespaceSerialization.Price price1 = new XMLNamespaceSerialization.Price();
price1.currency = "USD";
price1.price = 49.99M; // M suffix for decimal literals
book1.Title = "Advanced .NET";
book1.price = price1;
// Book2
XMLNamespaceSerialization.Book book2 = new XMLNamespaceSerialization.Book();
XMLNamespaceSerialization.Price price2 = new XMLNamespaceSerialization.Price();
price2.currency = "GBP";
price2.price = 39.99M; // M suffix for decimal literals
book2.Title = "Advanced C#";
book2.price = price2;
// Add books to collection
XMLNamespaceSerialization.Books books = new XMLNamespaceSerialization.Books();
books.alBooks.Add( book1 );
books.alBooks.Add( book2 );
/* Create XML namespace pairs */
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add( "YD", "www.diranieh.com" );
/* Serialize to file */
Stream stream = new FileStream( "Namespaces.xml", FileMode.Create, FileAccess.Write, FileShare.Write );
XmlSerializer serializer = new XmlSerializer( typeof( XMLNamespaceSerialization.Books ) );
serializer.Serialize( stream, books, namespaces );
stream.Close();
}
Output from the previous code is shown below:
<YD:alBooks>
<YD:Title>Advanced .NET
<YD:price currency="USD" price="49.99" />
</YD:alBooks>
<YD:alBooks>
<YD:Title>Advanced C#
<YD:price currency="GBP" price="39.99" />
</YD:alBooks>
Ref: http://www.diranieh.com/NETSerialization/XMLSerialization.htm
No comments:
Post a Comment