Common tool classes in C # (Utility Class) (iii)

Source: Internet
Author: User

I'm going to write this series today, which is mainly about XML serialization in C #, which I'm sure we'll always use, especially in WPF, where sometimes we need to keep our backstage data in the database. This allows the software to automatically load the data the next time it is started, because there are many fields in our model, and if it is not realistic to save it in isolation, it is a good idea to serialize these fields into XML strings and save them in the database. When we need this data we can also turn it into some fields, and finally achieve our effect, first we look at how it is implemented?

    public class Xmlutil {//<summary>//XML & DataContract Serialize & Deserialize Hel Per///</summary>//<typeparam name= "T" ></typeparam>//<param name= "Serialo Bject "></param>///<returns></returns> public static string serializer<t> (T Seri Alobject) where T:class {try {XmlSerializer ser = new XmlSerializer (typeof                (T));                System.IO.MemoryStream mem = new MemoryStream ();                XmlTextWriter writer = new XmlTextWriter (mem, Encoding.UTF8); Ser.                Serialize (writer, serialobject); Writer.                Close (); Return Encoding.UTF8.GetString (Mem.            ToArray ());            } catch (Exception ex) {return null;    }} public static T deserialize<t> (String str) where T:class {try {            XmlSerializer myserializer = new XmlSerializer (typeof (T));                        StreamReader mem2 = new StreamReader (New MemoryStream (System.Text.Encoding.UTF8.GetBytes (str)),                SYSTEM.TEXT.ENCODING.UTF8);            Return (T) myserializer.deserialize (MEM2);            } catch (Exception) {return null; }        }           }

The kind of XmlSerializer that Microsoft provides for us provides this possibility, and in the process of serialization we need to be aware that all properties must be serializable objects, such as BitmapImage, These objects, such as SolidColorBrush, are objects that cannot be serialized, and NULL is returned if serialized with the above method, and the correct way is to add the [XmlIgnore] description to these fields, so that they are skipped at serialization time, as in the following way.

        <summary>///Background color///        </summary>        private SolidColorBrush _backgroundcolor;        [XmlIgnore]        Public SolidColorBrush backgroundcolor        {            get            {                return _backgroundcolor;            }            Set            {                if (value! = _backgroundcolor)                {                    _backgroundcolor = value;                    OnPropertyChanged ("BackgroundColor");}}}        

So like the SolidColorBrush object above how to serialize it, here we choose to save the current color of the ARGB value in a byte array, in order to deserialize the time by Color.FromArgb way to restore, as in the following way.

        Byte[] Colorbyte=savedmodel.configurationbasemodel.backgroundcolorargb;            Color Backcolor=color.fromargb (colorbyte[0],colorbyte[1],colorbyte[2],colorbyte[3]);            Sourcebasemodel.backgroundcolor = new SolidColorBrush (BackColor);

So how do you save this object when it's serialized? The same principle we can do in the following way.

        <summary>///Background color///</summary> private SolidColorBrush _backgroundcolor;  [XmlIgnore] public SolidColorBrush backgroundcolor {get {return            _backgroundcolor; } set {if (value! = _backgroundcolor) {_backgroun                    Dcolor = value;                OnPropertyChanged ("BackgroundColor"); }}}///<summary>//Background color ARGB//</summary> private byte[] _b        Ackgroundcolorargb=new Byte[4];                [XmlArray ("ARGB"), XmlArrayItem ("value")] public byte[] Backgroundcolorargb {get {                    if (null! = _backgroundcolor) {color color = _backgroundcolor.color; _BACKGROUNDCOLORARGB[0] = color.                    A _BACKGROUNDCOLORARGB[1] = color.           R         _BACKGROUNDCOLORARGB[2] = color.                    G _BACKGROUNDCOLORARGB[3] = color.                B            } return _BACKGROUNDCOLORARGB; } set {if (value! = _backgroundcolorargb) {_backg                    Roundcolorargb = value;                OnPropertyChanged ("Backgroundcolorargb"); }                        }        }

This is found in actual use, just as a byte array must be classified by a type of identifier [XmlArray ("ARGB"), XmlArrayItem ("value")], after serializing it, We can see how this Backgroundcolorargb field is ultimately saved in what way?

This argb and value are deserialized into a byte array when deserializing.

In addition to these exceptions, sometimes it is often necessary to serialize the array of objects, so what is the principle? Here I use an example from someone else to do the relevant instructions.

XML serialization of an object array:

XML serialization of an array requires the XML node name of the array element to be specified using XmlArrayAttribute and Xmlarrayitemattribute;xmlarrayattribute. XmlArrayItemAttribute the XML node name of the specified array element.

The following code example:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Xml.Serialization;             Namespace usexmlserialization{class Program {static void Main (string[] args) {//Declare a Cat object var cwhite = new Cat {Color = ' white ', speed = ten, saying = ' white ' or black, so long as the cat can catch mi            CE, it is a good cat "};  var cblack = new Cat {Color = "Black", speed = ten, saying = "White or Black, so long as the cat can catch mice, it's a             Good cat "};             catcollection cc = new Catcollection {Cats = new cat[] {cwhite,cblack}};             Serialization of this object XmlSerializer serializer = new XmlSerializer (typeof (Catcollection)); Serializes the object output to the console serializer.             Serialize (Console.Out, CC);        Console.read (); }} [XmlRoot ("Cats")] public class Catcollection {[XmlArray ("Items"), XmlArrayItem ("item")] Pub    Lic cat[] Cats {get; set;} } [XmlrooT ("Cat")] public class Cat {//defines the attribute serialized as a cat node property [XmlAttribute ("color")] public string Col         or {get; set;}         Requires no serialization of the Speed property [XmlIgnore] public int speed {get; set;}    Sets the saying property to serialize to an XML child element [XmlElement ("saying")] public string saying {get; set;} }}

The end result is:

<?xml version= "1.0" encoding= "gb2312"? ><cats xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd= "Http://www.w3.org/2001/XMLSchema" >  <items>    <item color= "White" >      <saying> White or black, so long as the  cat can catch mice,  it's a good cat</saying>    </item>    <item Color= "Black" >      <saying>white or Black, so long as the  cat can catch mice,  it's a good cat</saying >    </item>  </items></cats>  

Let's go through this example to get an initial look at the knowledge of XML serialization.

Common tool classes in C # (Utility Class) (iii)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.