Aklımda Kalası Kelimeler

* давайте работать вместе
* Zarf ve Mazruf, Zerafet(xHoyratlık) ile aynı kökten(za-ra-fe) gelir
* Bedesten
* Suç subuta ermiştir - Suç sabit olmuştur
XmlArray etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
XmlArray etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

20 Kasım 2013 Çarşamba

Xml Serileştirmede XmlArray, XmlArrayItem, XmlAttribute, XmlSerializer, XmlType, XmlEnum, XmlIgnore, XmlInclude, IsNullable vd. incelemesi

Kodun içinde notlarım var. Örnek msdn den.

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

public class Run
{
    public static void Main()
    {
        Run test = new Run();
        test.SerializeDocument("books.xml");
    }

    public void SerializeDocument(string filename)
    {
        // Creates a new XmlSerializer.
        XmlSerializer s =
        new XmlSerializer(typeof(MyRootClass));

        // Writing the file requires a StreamWriter.
        TextWriter myWriter = new StreamWriter(filename);

        // Creates an instance of the class to serialize. 
        MyRootClass myRootClass = new MyRootClass();

        /* Uses a basic method of creating an XML array: Create and 
        populate a string array, and assign it to the 
        MyStringArray property. */

        string[] myString = { "Hello", "world", "!" };
        myRootClass.MyStringArray = myString;

        /* Uses a more advanced method of creating an array:
           create instances of the Item and BookItem, where BookItem 
           is derived from Item. */
        Item item1 = new Item();
        BookItem item2 = new BookItem();

        // Sets the objects' properties.
        item1.ItemName = "Widget1";
        item1.ItemCode = "w1";
        item1.ItemPrice = 231;
        item1.ItemQuantity = 3;

        item2.ItemCode = "w2";
        item2.ItemPrice = 123;
        item2.ItemQuantity = 7;
        item2.ISBN = "34982333";
        item2.Title = "Book of Widgets";
        item2.Author = "John Smith";

        // Fills the array with the items.
        Item[] myItems = { item1, item2 };

        // Sets the class's Items property to the array.
        myRootClass.Items = myItems;

        /* Serializes the class, writes it to disk, and closes 
           the TextWriter. */
        s.Serialize(myWriter, myRootClass);
        myWriter.Close();
    }
}

// This is the class that will be serialized. 
public class MyRootClass
{
    private Item[] items;

    /* Here is a simple way to serialize the array as XML. Using the
       XmlArrayAttribute, assign an element name and namespace. The
       IsNullable property determines whether the element will be 
       generated if the field is set to a null value. If set to true,
       the default, setting it to a null value will cause the XML
       xsi:null attribute to be generated. */

    /* IsNullable = true 
            <NULLveOLUSTURULacak xsi:nil="true" xmlns="http://www.IsNullable.com" /> */
    [XmlElement(ElementName = "NULLveOLUSTURULacak", IsNullable = true, Namespace = "http://www.IsNullable.com")]
    public string IsNullable_true_ornegi;

    /* IsNullable = false (değer atanmazsa da false gibi çalışır) 
            'null değeri olduğu için xml elemanı oluşturulmadı' */
    [XmlElement(ElementName = "NULLveOLUSTURULMAYAcak", IsNullable = false, Namespace = "http://www.IsNullable.com")]
    public string IsNullable_false_ornegi;
    
    
    
    [XmlArray(ElementName = "bomBosDizi", Namespace = "http://www.nullDegerliDizi.com", IsNullable = true)]
    public string[] bosDizi;
    /* IsNullable = true olan XmlArray özellikli field sonucu:
            <bomBosDizi xsi:nil="true" xmlns="http://www.nullDegerliDizi.com" />
     */

    /// <summary>
    /// 
    /// XmlArray Özelliğinin BASİT şekli
    /// 
    /// </summary>
    [XmlArray(ElementName = "MyStrings", Namespace = "http://www.cpandl.com", IsNullable = true)]
    public string[] MyStringArray;
    /* En temel haliyle XmlArray aynı tip dizi elemanları için bir xml elemanı altında toplayacaktır.
       Sonuç:
        <MyStrings xmlns="http://www.cpandl.com">
          <string>Hello</string>
          <string>world</string>
          <string>!</string>
        </MyStrings>
     */


    [XmlArray(ElementName = "Dizi_Kok_Elemani")]
    [XmlArrayItem("Eleman_Etiketi")]
    public string[] stringDizi =  { "Hello", "world", "!" };
    /*
        <Dizi_Kok_Elemani>
          <Eleman_Etiketi>Hello</Eleman_Etiketi>
          <Eleman_Etiketi>world</Eleman_Etiketi>
          <Eleman_Etiketi>!</Eleman_Etiketi>
        </Dizi_Kok_Elemani>
     */


    /// <summary>
    /// 
    /// XmlArray Özelliğinin KARMAŞIK şekli
    /// 
    /// </summary>
    [XmlArrayItem(ElementName = "Item",     IsNullable = true, Type = typeof(Item),     Namespace = "http://www.cpandl.com"),
     XmlArrayItem(ElementName = "BookItem", IsNullable = true, Type = typeof(BookItem), Namespace = "http://www.cohowinery.com")]
    [XmlArray]
    public Item[] Items
    {
        get { return items; }
        set { items = value; }
    }
    /*
     Items propertysi Item cinsinden bir dizi alır.
     Yani hem Item, hem BookItem türü verileri alabilir.
     Serileştirilecek nesnenin Items elemanı hem Item hem de BookItem 
     türünde iki nesne alacağı için dizi içindeki eleman türüne göre serileştirme çalışacak
     Sonuç:
      <Items>
        <Item xmlns="http://www.cpandl.com">
          <OrderItem>Widget1</OrderItem>
          <ItemCode>w1</ItemCode>
          <ItemPrice>231</ItemPrice>
          <ItemQuantity>3</ItemQuantity>
        </Item>
        <BookItem xmlns="http://www.cohowinery.com">
          <ItemCode>w2</ItemCode>
          <ItemPrice>123</ItemPrice>
          <ItemQuantity>7</ItemQuantity>
          <Title>Book of Widgets</Title>
          <Author>John Smith</Author>
          <ISBN>34982333</ISBN>
        </BookItem>
      </Items> 
     */


    [
        XmlArrayItem(Type = typeof (BookItem)),
        XmlArrayItem(Type = typeof (string)),
        XmlArrayItem(Type = typeof (int))
    ] 
    public object[] KarisikTipler =
    {
        "Bu", 1, new BookItem()
                 {
                     Author = "Cem",
                     ISBN = "93845934",
                     ItemCode = "item kod 10",
                     ItemName = "item adı",
                     ItemPrice = 1.2m,
                     ItemQuantity = 10,
                     Title = "Başlık şu, bu, o"
                 }
    };
    /* Her dizi elemanı string, int ve BookItem tipindeyse serileştirilecek değilse istisna fırlatacak.
        <KarisikTipler>
          <string>Bu</string>
          <int>1</int>
          <BookItem>
            <OrderItem>item adı</OrderItem>
            <ItemCode>item kod 10</ItemCode>
            <ItemPrice>1.2</ItemPrice>
            <ItemQuantity>10</ItemQuantity>
            <Title>Başlık şu, bu, o</Title>
            <Author>Cem</Author>
            <ISBN>93845934</ISBN>
          </BookItem>
        </KarisikTipler>
     */

    /// 
    /// xml çıktısı:
    ///     <EmpStatus>Triple</EmpStatus>
    /// 
    public EmployeeStatus EmpStatus=EmployeeStatus.Three;
}

public enum EmployeeStatus
{
    [XmlEnum(Name = "Single")]
    One,
    [XmlEnum(Name = "Double")]
    Two,
    [XmlEnum(Name = "Triple")]
    Three
}


public class Item
{
    [XmlElement(ElementName = "OrderItem")]
    public string ItemName;
    public string ItemCode;
    public decimal ItemPrice;
    public int ItemQuantity;
}

public class BookItem : Item
{
    public string Title;
    public string Author;
    public string ISBN;
}


/// <summary>
/// Şu nesne için:
/// 
///    public KitapItem kit = new KitapItem()
///                           {
///                               Author = "Kitapçı Cem",
///                               ISBN = "---1---",
///                               ItemCode = "item kodum oldu",
///                               ItemName = "item adım yok oldu",
///                               ItemPrice = 10.2m,
///                               ItemQuantity = 23,
///                               Title = "illa başlık, hep başlık"
///                           };
/// 
/// 
/// xml sonucu:
/// 
///  <kit d2p1:baslik="illa başlık, hep başlık" xmlns:d2p1="attribute_nameSpeysi">
///    <OrderItem xmlns="kitapNameSpace">item adım yok oldu</OrderItem>
///    <ItemCode xmlns="kitapNameSpace">item kodum oldu</ItemCode>
///    <ItemPrice xmlns="kitapNameSpace">10.2</ItemPrice>
///    <ItemQuantity xmlns="kitapNameSpace">23</ItemQuantity>
///    <Author xmlns="kitapNameSpace">Kitapçı Cem</Author>
///    <ISBN xmlns="kitapNameSpace">---1---</ISBN>
///  </kit>
/// 
/// </summary>
[XmlType(TypeName = "KitapEleman", Namespace = "kitapNameSpace")]
public class KitapItem : Item
{
    [XmlAttribute(Namespace = "attribute_nameSpeysi", AttributeName = "baslik", DataType = "normalizedString")]
    public string Title;
    public string Author;
    public string ISBN;
}

<?xml version="1.0" encoding="utf-8"?>
<MyRootClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <NULLveOLUSTURULacak xsi:nil="true" xmlns="http://www.IsNullable.com" />
  <bomBosDizi xsi:nil="true" xmlns="http://www.nullDegerliDizi.com" />
  <MyStrings xmlns="http://www.cpandl.com">
    <string>Hello</string>
    <string>world</string>
    <string>!</string>
  </MyStrings>
  <Items>
    <Item xmlns="http://www.cpandl.com">
      <OrderItem>Widget1</OrderItem>
      <ItemCode>w1</ItemCode>
      <ItemPrice>231</ItemPrice>
      <ItemQuantity>3</ItemQuantity>
    </Item>
    <BookItem xmlns="http://www.cohowinery.com">
      <ItemCode>w2</ItemCode>
      <ItemPrice>123</ItemPrice>
      <ItemQuantity>7</ItemQuantity>
      <Title>Book of Widgets</Title>
      <Author>John Smith</Author>
      <ISBN>34982333</ISBN>
    </BookItem>
  </Items>
</MyRootClass>

XmlAttribute bir yerde tanımlıysa, o field ya da property nin tipindeki(class,struct vs.) [XmlType(......)] bir işe yaramaz.
KitapItem sınıfının Title fieldı için farklı bir namespace tanımladık (attribute_namepseysi) ve bunun için d2p1 oluşturulup özelliğin önüne konulduğuna dikkat edelim emi...

Enum gösterimi için [XmlEnum (Name = "enumGorunecekAdi")] kullanılır


XmlIgnore ile serileştirilmesini istemediğimiz field, prop vs. seçilir


XmlInclude ile hangi tiplerin serileştirilip serileştirilmeyeceği belirlenir