C #:. NET serialization and deserialization [XmlElement ("Node name")] [XmlAttribute ("Node Properties")] (next)

Source: Internet
Author: User
Tags net serialization

Describes XML serialization

. NET Framework Developer's Guide
Serialization is the process of converting an object into a format that is easy to transfer. For example, you can serialize an object and then use HTTP to transfer the object between the client and the server over the Internet. At the other end, deserialization reconstructs the object from the stream.

XML serialization serializes only the public fields and property values of an object into an XML stream. XML serialization does not include type information. For example, if you have a book object that exists in the Library namespace, there is no guarantee that it will be deserialized into an object of the same type.

Note XML serialization does not convert methods, indexers, private fields, or read-only properties (except for read-only collections). To serialize all the fields and properties of an object (public and private), use BinaryFormatter instead of using XML serialization.

The main class in XML serialization is the XmlSerializer class, and the most important method is the Serialize and deserialize methods. The XML stream generated by XmlSerializer conforms to the recommendations of the World Wide Web Consortium (www.w3.org) XML Schema definition language (XSD) 1.0. In addition, the resulting data type conforms to the document titled "XML Schema Part 2:datatypes" (The second section of XML Schemas: data types).

The data in an object is described by programming language constructs such as classes, fields, properties, primitive types, arrays, or even embedded XML in the form of XmlElement or XmlAttribute objects. You can create your own classes with attribute annotations, or use the XML Schema Definition tool to generate classes based on an existing XML schema.

If you have an XML schema, you can run the XML Schema Definition tool to generate a set of classes that are strongly typed as schemas and annotated with attributes. When an instance of such a class is serialized, the resulting XML conforms to the XML schema. With such a class, you can program against an object model that is easy to manipulate, while ensuring that the resulting XML conforms to the XML schema. This is a replacement method for parsing and writing XML streams using other classes in the. NET Framework, such as the XmlReader and XmlWriter classes. (For more information about using these classes, see Using XML in the. NET Framework.) These classes enable you to parse any XML stream. In contrast, use XmlSerializerwhen an XML stream is required to conform to a known XML schema.

property controls the XML stream generated by the XmlSerializer class, allowing you to set the XML namespace, element name, attribute name, and so on for the XML stream. For more information about these properties and how they control XML serialization, see Using Attributes to control XML serialization. For a table that lists those properties that control the generated XML, see properties that Control XML serialization.

The XmlSerializer class can further serialize objects and generate encoded SOAP XML streams. The resulting XML conforms to section 5th of the World Wide Web Consortium document titled "Simple Object Access Protocol (SOAP) 1.1". For more information about this procedure, see Generating SOAP messages with XML serialization. For property sheets that control the generated XML, see properties that Control encoded SOAP serialization.

The XmlSerializer class generates SOAP messages that are created and passed to XML Web services by XML Web services. To control SOAP messages, you can apply attributes to classes, return values, parameters, and fields in an XML Web services file (. asmx). You can use both the properties listed in control XML serialization properties and the properties listed in Control encoded SOAP serialization properties, because XML Web services can use text styles, or you can use encoded SOAP styles. For more information about using attributes to control the XML generated by XML Web services, see XML Serialization for XML Web services. For more information about soap and XML Web services, see Customizing SOAP messages.

Protecting XmlSerializer applications

When you create an application that uses XmlSerializer , you should understand the following points and their impact:

  • XmlSerializer creates a C # file (. cs file) and compiles it as a. dll file, which is located in the directory specified by the TEMP environment variable, and the DLL files are serialized.

    Code and DLLs are susceptible to malicious process attacks when they are created and compiled. If you are using a computer that is running Microsoft Windows NT 4.0 or later, you may have two or more users sharing a temporary directory. Sharing a temporary directory is risky if the following two scenarios exist: (1) Two accounts have different security privileges, and (2) a highly privileged account runs an application that uses XmlSerializer . In this case, a user can replace the compiled. cs or. dll file, thereby undermining the security of the computer. To avoid this problem, always make sure that each account on your computer has its own profile. If you can guarantee this, by default, the TEMP environment variable will specify a different directory for different accounts.

  • If a malicious user sends a persistent XML data stream (denial of service attack) to the WEB server,XmlSerializer will continue to process this data until the computer resources are insufficient to stop.

    If you are using a computer that is running Internet Information Services (IIS) and your application is running under IIS, you can avoid such attacks. IIS has a control gate that prohibits the processing of data streams that are larger than the set number (the default is 4 KB). If you are creating an application that does not use IIS and the application uses XmlSerializer for deserialization, you should implement a similar control gate to prevent denial of service attacks.

  • XmlSerializer will use any type given to it, serialize the data, and run any code.

    There are two ways to put a threat on a malicious object. One is to run malicious code, and the other is to insert malicious code into a C # file created by XmlSerializer . In the first case, if a malicious object tries to run a destructive process, code access security will help prevent any damage. In the second case, it is theoretically possible for a malicious object to insert code into a C # file created by XmlSerializer in some way. Although this issue has been thoroughly tested and such attacks are considered impossible, you should be careful not to serialize data of unknown types that are not trustworthy.

  • Important data that has been serialized may be vulnerable to attack.

    XmlSerializer After the data is serialized, the data can be stored as an XML file or stored in another data store. If other processes can access your data store, or you can see it on your Intranet or the Internet, the data can be stolen and used maliciously. For example, if you create an application that serializes an order that contains a credit card number, this data is very important. To prevent this from happening, always protect your data store and take privacy measures on your data.

Serialization of simple classes

The following example shows a simple class with a public field:

[Visual Basic] Public Class OrderForm Public    OrderDate as Datetimeend class[c#]public Class orderform{public    DateTime OrderDate;}

When an instance of this class is serialized, the instance may resemble the following code:

<OrderForm>    <OrderDate>12/12/01</OrderDate></OrderForm>

For more examples of serialization, see examples of XML serialization.

Items that can be serialized

Using the XmLSerializer class, you can serialize the following items.

    • Public read/write properties and fields for public classes
    • A class that implements ICollection or IEnumerable . (Note that only the collection is serialized, but the public properties are not.) )
    • The XmlElement object.
    • The XmlNode object.
    • The DataSet object.
Serialization and deserialization of objects

To serialize an object, first create the object to serialize and set its public properties and fields. To do this, you must determine the transport format (either as a stream or as a file) to store the XML stream. For example, if the XML stream must be persisted in a permanent form, the FileStream object is created. When you deserialize an object, the transport format determines whether you will create a stream or a file object. Once you have determined the transport format, you can call the Serialize or deserialize method as needed.

Serializing objects

    1. creates an object and sets its public fields and properties.
    2. constructs   using the type of the object; XmlSerializer . For more information, see   XmlSerializer   class constructors.
    3. calls   Serialize   method to generate an XML stream representation or a file representation of the public properties and fields of the object. The following example creates a file.
       [Visual basic]dim myObject as Myserializableclass = New myserializableclass () ' Insert code to set properties and Fields of the object. Dim Myserializer as XmlSerializer = New XmlSerializer (GetType (Myserializableclass)) ' to write to a file, create a STREAMWR Iter object. Dim mywriter as StreamWriter = New StreamWriter ("Myfilename.xml") myserializer.serialize (Mywriter, MyObject) [C #] Myserializableclass myObject = new Myserializableclass ();//Insert code to set properties and fields of the object. XmlSerializer myserializer = new XmlSerializer (typeof (Myserializableclass));/To write to a file, create a StreamWriter o Bject.
      StreamWriter mywriter = new StreamWriter ("Myfilename.xml"); Myserializer.serialize (Mywriter, myObject); 

Deserializing objects

  1. Constructs a XmlSerializerusing the type of the object being deserialized.
  2. CallDeserializemethod to produce a copy of the object. When deserializing, you must cast the returned object to the type of the original object, as shown in the following example. The following example deserializes the object into a file, although it can also be deserialized into a stream.
     [Visual basic]dim myObject as Myserializableclass ' constructs an instance of the XmlSerializer with the type ' of object is being deserialized. Dim Myserializer as XmlSerializer = New XmlSerializer (GetType (Myserializableclass)) ' to read the file, creates a Filestrea M.dim myFileStream as FileStream = _new FileStream ("Myfilename.xml", FileMode.Open) ' Calls The deserialize method and cast s to the object type.myobject = CType (_myserializer.deserialize (myFileStream), myserializableclass) [C #] Myserializableclass myobject;//constructs an instance of the XmlSerializer with the type//of object it is being Deseri Alized. XmlSerializer myserializer = new XmlSerializer (typeof (Myserializableclass));/To read the file, creates a Filestream.fil eSTREAM myFileStream = new FileStream ("Myfilename.xml", FileMode.Open);//Calls The deserialize method and casts to the OB Ject Type.myobject = (myserializableclass) myserializer.deserialize (myFileStream) 

For more examples of XML serialization, see Examples of XML serialization.

Benefits of using XML serialization

The XmlSerializer class gives you complete and flexible control when you serialize objects to XML. If you are creating an XML Web services, you can apply properties that control serialization to classes and members to ensure that the XML output conforms to a specific schema.

For example,XmlSerializer enables you to:

    • Specifies whether the field or property should be encoded as an attribute or an element.
    • Specifies the XML namespace to use.
    • Specifies the name of the element or attribute if the field or property name is not appropriate.

Another benefit of XML serialization is that as long as the resulting XML stream conforms to the given schema, there is no constraint on the application being developed. Suppose there is a schema for describing a book that has a title, author, publisher, and ISBN numbering element. You can develop an application that processes XML data in any way you want (for example, as a book order, or as a book list). In either case, the only requirement is that the XML stream should conform to the specified XML Schema definition language (XSD) schema.

XML Serialization Considerations

When you use the XmlSerializer class, you should consider the following scenarios:

  • The serialized data contains only the data itself and the structure of the class. Does not include type identification and assembly information.
  • Only public properties and fields can be serialized. If you need to serialize non-public data, use the BinaryFormatter class instead of XML serialization.
  • The class must have a default constructor that will be serialized by XmlSerializer .
  • The
  • cannot serialize methods.
  • XmlSerializer   can handle implementation   in different ways; IEnumerable   or   ICollection   Classes (provided these classes meet certain requirements). Implement &NBSP; The class for IEnumerable   must implement a public   with a single argument; Add   method. The parameters of the Add   method must be the   returned from   GetEnumerator   method; IEnumerator.Current   property returns the same type (polymorphic). In addition to implementing &NBSP, IEnumerable   also implements &NBSP; ICollection   classes such as CollectionBase ) must have a public   that takes an integer; Item   Indexed property (indexer in C #), and it must have an integer type of public   Count   properties. Passed to   the Add   method must have the same type as the one returned from   Item   property, or the same type as a base of that type. For a class that implements &NBSP; ICollection  , the value to serialize is retrieved from the index  , Item   property, rather than by calling   GetEnumerator   to retrieve. Also note that public fields and properties will not be serialized except for a public field that returns another collection class (Implementing   ICollection   's collection Class). For an example, see examples of  xml serialization.
XSD Data Type Mappings

The World Wide Web Consortium (www.W3.org) document titled "XML Schema Part 2:datatypes" Specifies the simple data types that are allowed in the XML Schema definition language (XSD) schema. For many types in these data types (for example,int and decimal), there is a corresponding data type in the. NET Framework. However, some XML data types do not have corresponding data types in the. NET Framework (for example,nmtoken data types). In such a case, if you use the XML Schema Definition tool (Xsd.exe) to generate a class from the schema, the appropriate attribute is applied to the member of the string type and its DataType property is set to the XML data type name. For example, if the schema contains an element named "MyToken" with a data type of XML data type nmtoken , the generated class may contain members from the following example.

[Visual basic]<xmlelement (datatype:= "NmToken") >public MyToken as string[c#][xmlelement (DataType = "NMTOKEN")] public string MyToken;

Similarly, if you create a class that must conform to a specific XML Schema (XSD), you should apply the appropriate attribute and set its DataType property to the desired XML data type name.

For a complete list of type mappings, see the DataType properties of any of the following attribute classes: Soapattributeattribute, SoapElementAttribute, XmlArrayItemAttribute , XmlAttributeAttribute, XmlElementAttribute, or XmlRootAttribute.

C #:. NET serialization and deserialization [XmlElement ("Node name")] [XmlAttribute ("Node Properties")] (next)

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.