asp.net XML serialization for custom objects

Source: Internet
Author: User

ASP tutorials XML Serialization for. NET Custom objects

The System.Xml.Serialization namespace has a series of attribute classes to control the control of complex type serialization. such as XmlElementAttribute, XmlAttributeAttribute, XmlArrayAttribute, XmlArrayItemAttribute, XmlRootAttribute and so on.

To see a small example, there is a custom class Cat,cat class that has three properties, respectively, Color,saying,speed.

Namespace Usexmlserialization
{
Class Program
{
static void Main (string[] args)
{
Declaring a Cat object
var c = new Cat {Color = "white", Speed = ten, saying = "White or black, so long as the cat can catch mice, it is a good Cat "};

Serialization of this object
XmlSerializer serializer = new XmlSerializer (typeof (Cat));

Serializing an object to the console
Serializer. Serialize (Console.Out, C);

Console.read ();
}
}

[XmlRoot ("Cat")]
public class Cat
{
Defines a property that is serialized as a cat node for a color property
[XmlAttribute ("Color")]
public string Color {get; set;}

Requires no serialization of speed properties
[XmlIgnore]
public int Speed {get; set;}

To set the saying property to be serialized as an XML child element
[XmlElement ("saying")]
public string saying {get; set;}
}
}<span style= "Font-family:verdana, Arial, Helvetica, Sans-serif" face= "Verdana, Arial, Helvetica, Sans-serif" > <span class=apple-style-span style= "FONT-SIZE:14PX; line-height:21px; White-space:normal ">
</SPAN></SPAN>


You can use XmlElement to specify a property to be serialized as a child node (which is serialized as a child node by default) or by using the XmlAttribute attribute to serialize properties to an XML node, or by XmlIgnore attribute grooming to require that the serializer not serialize the decorated property.

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.