Csharp/CSharp Tutorial/XML/Xml serialization

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Serialization of an object marked with XmlAttribute and XmlIgnore

using System;
using System.IO;
using System.Xml.Serialization;
    public class Customer
    {
        [XmlAttribute()]
        public string FirstName { get; set; }
        [XmlIgnore()]
        public string LastName { get; set; }
        public string EmailAddress { get; set; }
        public override string ToString()
        {
            return string.Format("{0} {1}\nEmail:   {2}",FirstName, LastName, EmailAddress);
        }
    }
    public class Tester
    {
        static void Main()
        {
            Customer c1 = new Customer{
                              FirstName = "A",
                              LastName = "B",
                              EmailAddress = "o@a.ru"
                          };
            XmlSerializer serializer = new XmlSerializer(typeof(Customer));
            StringWriter writer = new StringWriter();
            serializer.Serialize(writer, c1);
            string xml = writer.ToString();
            Console.WriteLine("Customer in XML:\n{0}\n", xml);
            Customer c2 = serializer.Deserialize(new StringReader(xml)) as Customer;
            Console.WriteLine("Customer in Object:\n{0}", c2.ToString());
        }
    }

Serialize a list of object to Xml with Linq

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
    public class Customer{
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailAddress { get; set; }
        public override string ToString()
        {
            return string.Format("{0} {1}\nEmail:   {2}",FirstName, LastName, EmailAddress);
        }
    }
    public class Tester{
        static void Main(){
            List<Customer> customers = new List<Customer>{
                new Customer { FirstName = "A", 
                               LastName = "G",
                               EmailAddress = "o@a.ru"},
                new Customer { FirstName = "B", 
                               LastName = "C",
                               EmailAddress = "k@a.ru" },
                new Customer { FirstName = "D", 
                               LastName = "C",
                               EmailAddress = "d@a.ru" },
                new Customer { FirstName = "E", 
                               LastName = "G",
                               EmailAddress = "j@a.ru" },
                new Customer { FirstName = "L", 
                               LastName = "H",
                               EmailAddress = "l@a.ru" }
            };
            XmlDocument customerXml = new XmlDocument();
            XmlElement rootElem = customerXml.CreateElement("Customers");
            customerXml.AppendChild(rootElem);
            foreach (Customer customer in customers){
                XmlElement customerElem = customerXml.CreateElement("Customer");
                XmlAttribute firstNameAttr = customerXml.CreateAttribute("FirstName");
                firstNameAttr.Value = customer.FirstName;
                customerElem.Attributes.Append(firstNameAttr);
                XmlAttribute lastNameAttr = customerXml.CreateAttribute("LastName");
                lastNameAttr.Value = customer.LastName;
                customerElem.Attributes.Append(lastNameAttr);
                XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
                emailAddress.InnerText = customer.EmailAddress;
                customerElem.AppendChild(emailAddress);
                rootElem.AppendChild(customerElem);
            }
            Console.WriteLine(customerXml.OuterXml);
        }
    }

Serialize/Deserialize Xml: deal with element list

using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
public class MainClass
{
  private static void Main()
  {
    // Create the product catalog.
    ProductCatalog catalog = new ProductCatalog("New Catalog", DateTime.Now.AddYears(1));
    Product[] products = new Product[2];
    products[0] = new Product("Product 1", 42.99m);
    products[1] = new Product("Product 2", 202.99m);
    catalog.Products = products;
    // Serialize the order to a file.
    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);
  }
}
[XmlRoot("productCatalog")]
public 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;
  }
}
<?xml version="1.0" encoding="gb2312"?>
<productCatalog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2
001/XMLSchema">
  <catalogName>New Catalog</catalogName>
  <expiryDate>2008-03-25</expiryDate>
  <products>
    <product>
      <productName>Product 1</productName>
      <productPrice>42.99</productPrice>
      <inStock>false</inStock>
    </product>
    <product>
      <productName>Product 2</productName>
      <productPrice>202.99</productPrice>
      <inStock>false</inStock>
    </product>
  </products>
</productCatalog>

Specify format and indentation for object XML serialization

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class MainClass
{
  static void Main() 
  {
    try
    {
      MemberList g = new MemberList( "group name" );
      g.members[0] = new Member( "mem 1" );
      g.members[1] = new Member( "mem 2" );
      g.members[2] = new Member( "mem 3" );
      StringWriter sw = new StringWriter();
      XmlTextWriter tw = new XmlTextWriter( sw );
      tw.Formatting = Formatting.Indented;
      tw.Indentation = 4;
      XmlSerializer ser = new XmlSerializer( typeof( MemberList ) );
      ser.Serialize( tw, g );
      tw.Close();
      sw.Close();
      Console.WriteLine(sw.ToString());
    }
    catch( Exception exc )
    {
      Console.WriteLine(exc.Message );
    }
  }
}
public class MemberList
{
  public MemberList()
  {
    members = new Member[5];
  }
  public MemberList( string name ) : this()
  {
    m_name = name;
  }
  public string m_name;
  public Member[] members;
}
public class Member
{
  public Member()
  {
  }
  public Member( string name ) :this()
  {
    m_name = name;
  }
  public string m_name;
}
<?xml version="1.0" encoding="utf-16"?>
<MemberList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/
XMLSchema">
    <m_name>group name</m_name>
    <members>
        <Member>
            <m_name>mem 1</m_name>
        </Member>
        <Member>
            <m_name>mem 2</m_name>
        </Member>
        <Member>
            <m_name>mem 3</m_name>
        </Member>
        <Member xsi:nil="true" />
        <Member xsi:nil="true" />
    </members>
</MemberList>

Specify the XmlRoot and XmlAttribute for XML serialization

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

[XmlRoot("EmployeeList")]
public class EmployeeList {
    private ArrayList employeeList = new ArrayList();
    public EmployeeList( ) {
    }
    [XmlElement("employee")]
     public Employee[] Employees {
        get { 
            Employee[] employees = new Employee[ employeeList.Count ];
            employeeList.CopyTo( employees );
            return employees; 
        }
        set { 
            Employee[] employees = (Employee[])value;
            employeeList.Clear();
            foreach( Employee i in employees )
               employeeList.Add( i );
        }
    }
    public void AddEmployee( Employee employee ) {
        employeeList.Add( employee );
    }
    public Employee this[string firstName] {
        get {
            foreach( Employee i in employeeList )
                if( i.firstName == firstName )
                   return i;
            throw( new Exception("Employee not found") );
        }
    }
    public void DisplayEmployees( ) {
        foreach( Employee i in employeeList )
            Console.WriteLine( i );
    }
}
public class Employee {
     [XmlAttribute("firstName")]   public string  firstName;
     [XmlAttribute("lastName")]    public string  lastName;
     [XmlAttribute("salary")]      public double  salary;
     [XmlAttribute("number")]      public int     number;
    
     public Employee( ) {  }
     public Employee( string f, string l, double s, int n ) {
        firstName = f;
        lastName = l;
        salary = s;
        number = n;
     }
     public override string ToString( ) {
        object[] o = new object[] { firstName, lastName, salary, number };
        return string.Format("{0,-5} {1,-10} ${2,5:#,###.00} {3,3}", o);
     }
}
public class MainClass {
    public static void Main( ) {
        EmployeeList employList = new EmployeeList( );
        employList.AddEmployee( new Employee("A","p",  123.15,100) );
        employList.AddEmployee( new Employee("B","c",  712.50, 25) );
        employList.AddEmployee( new Employee("C","wt", 132.35, 10) );
        employList.DisplayEmployees( );
        Console.WriteLine("Serialization in progress");
        XmlSerializer s = new XmlSerializer( typeof( EmployeeList ) );
        TextWriter w = new StreamWriter("employList.xml");
        s.Serialize( w, employList );
        w.Close();
        Console.WriteLine("Serialization complete\n\n");
        Console.WriteLine("Deserialization in progress");
        EmployeeList employList2 = new EmployeeList( );
        TextReader r = new StreamReader( "employList.xml" );
        employList2 = (EmployeeList)s.Deserialize( r );
        r.Close( );
        Console.WriteLine("Deserialization complete");
        employList2.DisplayEmployees();
   }
    
}
A     p          $123.15 100
B     c          $712.50  25
C     wt         $132.35  10
Serialization in progress
Serialization complete

Deserialization in progress
Deserialization complete
A     p          $123.15 100
B     c          $712.50  25
C     wt         $132.35  10

Using XmlSerializer to Serialize a Linq object

using System;
using System.IO;
using System.Xml.Serialization;
    public class Customer
    {
        public string FirstName;
        public string LastName;
        public string EmailAddress;
        public override string ToString()
        {
            return string.Format("{0} {1}\nEmail:   {2}",FirstName, LastName, EmailAddress);
        }
    }
    public class Tester
    {
        static void Main()
        {
            Customer c1 = new Customer{
                              FirstName = "A",
                              LastName = "G",
                              EmailAddress = "o@a.ru"
                          };
            XmlSerializer serializer = new XmlSerializer(typeof(Customer));
            StringWriter writer = new StringWriter();
            serializer.Serialize(writer, c1);
            string xml = writer.ToString();
            Console.WriteLine("Customer in XML:\n{0}\n", xml);
            Customer c2 = serializer.Deserialize(new StringReader(xml)) as Customer;
            Console.WriteLine("Customer in Object:\n{0}", c2.ToString());
        }
    }

XML Serialization Sample

using System;
using System.Xml.Serialization;
  [XmlRoot("cell-phone")]
  public class CellPhone {
    public CellPhone () {
    }
    [XmlAttribute("name")]
    public string Name {
      get {return this._name;}
      set {this._name = value;}
    }
    [XmlAttribute("year")]
    public int Year {
      get {return this._year;}
      set {this._year = value;}
    }
    [XmlElement("description")]
    public string Description {
      get {return this._description;}
      set {this._description = value;}
    }
    private string _name = "";
    private int _year = 2000;
    private string _description = "";
  }
  class XMLSerializationSample {
    static void Main(string[] args) {
      XmlSerializer serializer = new XmlSerializer(Type.GetType("CellPhone"));
      CellPhone cellPhone = new CellPhone();
      cellPhone.Description = "Some description";
      cellPhone.Name = "AAA";
      serializer.Serialize(Console.Out, cellPhone);
    }
  }

XML serialization with namespace setting

using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
class MainClass{
  public static void Main(){
     try {
         ShapedRoot sr = new ShapedRoot();
         sr.node = new Shaped();
         sr.node.s1 = "a value";
         sr.node.s2 = "another value";
         sr.node.s3 = "uuid:1AE0964A-2B30-4a02-96F2-325B92B4E92C";
         StringWriter sw = new StringWriter();
         XmlTextWriter tw = new XmlTextWriter( sw );
         tw.Formatting = Formatting.Indented;
         tw.Indentation = 4;
         XmlSerializer ser = new XmlSerializer( typeof( ShapedRoot ) );
         ser.Serialize( tw, sr );
         tw.Close();
         sw.Close();
     }
     catch( Exception exc )
     {
         Console.WriteLine( exc.Message );
     }
 
  }
}
[XmlRoot( ElementName="sroot", Namespace="urn:my-examples:shaping" )]
public class ShapedRoot
{
    public ShapedRoot()
    {
    }
    public Shaped node;
}
[XmlType( Namespace="urn:my-examples:shaping" )]
public class Shaped
{
    public Shaped()
    {
    }
    [XmlAttribute]
    public string s1;
    [XmlElement( ElementName = "string2" )]
    public string s2;
    [XmlElement( DataType = "anyURI" )]
    public string s3;
}