03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

XML Serialization ❘ 569<br />

Each Order element holds other elements that contain information about the program’s<br />

Order object. The OrderItems element holds a sequence of OrderItem objects to represent<br />

an OrderItem object’s OrderItems array.<br />

Obvious XML<br />

The XML serialization’s structure is so intuitive that you could easily serialize and<br />

deserialize objects yourself by hand if necessary. The only remarkable thing about it is<br />

that it all happens automatically. You don’t need to tell the serializer what properties<br />

and fields the Customer, Order, and OrderItem classes have; what their data types<br />

are; or whether they are simple values (such as int and string) or complex values<br />

(such as OrderItem and List). The serializer figures that out all by itself.<br />

The serializer uses reflection to analyze the classes and determine what values it must<br />

save and what their names are. You’ll learn how your programs can use reflection in<br />

the next chapter.<br />

Controlling Serialization<br />

The serialization shown in the preceding section is straightforward and reasonably intuitive, but<br />

there are times when you might want to change the way an object is serialized.<br />

For example, the previous serialization is easy to understand but it’s quite verbose. Perhaps you<br />

would rather store this data:<br />

Like this:<br />

<br />

Tape<br />

12<br />

0.75<br />

<br />

<br />

The result is more concise and possibly easier to read.<br />

For another example, suppose your program saves a customer’s order data and you want to use<br />

that data in another program. Unfortunately, the other program stores a Customer object’s order<br />

information in an Order[] named CustomerOrders instead of a List named Orders.<br />

At this point you might realize that you could use XSLT to transform your serialization into a format<br />

that the other program could deserialize. That would certainly work (and would let you make other<br />

transformations that you can’t with the techniques that follow) but it would be extra work and require<br />

another processing step.<br />

Fortunately, the System.Xml.Serialization namespace defines attributes that you can use to gain<br />

some control over the serialization process. You add these attributes to classes or the properties and<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!