Use XML Serialization with Custom Objects : Xml Serialization « XML « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Design Patterns
8.Development Class
9.Event
10.File Stream
11.Generics
12.GUI Windows Form
13.Language Basics
14.LINQ
15.Network
16.Office
17.Reflection
18.Regular Expressions
19.Security
20.Services Event
21.Thread
22.Web Services
23.Windows
24.Windows Presentation Foundation
25.XML
26.XML LINQ
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » XML » Xml SerializationScreenshots 
Use XML Serialization with Custom Objects
 

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

[XmlRoot("productCatalog")]
class ProductCatalog {
    [XmlElement("catalogName")]
    public string CatalogName;

    [XmlElement(ElementName = "expiryDate", DataType = "date")]
    public DateTime ExpiryDate;

    [XmlArray("products")]
    [XmlArrayItem("product")]
    public Product[] Products;

    public ProductCatalog() { }
    public ProductCatalog(string catalogName, DateTime expiryDate) {
        this.CatalogName = catalogName;
        this.ExpiryDate = expiryDate;
    }
}

public class Product {
    [XmlElement("productName")]
    public string ProductName;

    [XmlElement("productPrice")]
    public decimal ProductPrice;

    [XmlElement("inStock")]
    public bool InStock;

    [XmlAttributeAttribute(AttributeName = "id", DataType = "integer")]
    public string Id;

    public Product() {}

    public Product(string productName, decimal productPrice) {
        this.ProductName = productName;
        this.ProductPrice = productPrice;
    }
}


public class MainClass {
    private static void Main() {
        ProductCatalog catalog = new ProductCatalog("New Catalog", DateTime.Now.AddYears(1));
        Product[] products = new Product[2];
        products[0new Product("Product 1"42.99m);
        products[1new Product("Product 2"202.99m);
        catalog.Products = products;

        XmlSerializer serializer = new XmlSerializer(typeof(ProductCatalog));
        FileStream fs = new FileStream("ProductCatalog.xml", FileMode.Create);
        serializer.Serialize(fs, catalog);
        fs.Close();

        catalog = null;

        fs = new FileStream("ProductCatalog.xml", FileMode.Open);
        catalog = (ProductCatalog)serializer.Deserialize(fs);

        serializer.Serialize(Console.Out, catalog);
    }
}



           
         
  
Related examples in the same category
1.Serialize List of Objects
2.Use XmlSerializer
3.Set Xml Attribute when serilzation
4.XmlRootAttribute
5.Takes an XML file and exports the Object it holds
6.Converts an XML string to an object
7.Deserializes/Serializes an xml document back into an object
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.