15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Attributes, names, and namespaces<br />

By default, fields and properties serialize to an XML element. You can request an<br />

XML attribute be used instead as follows:<br />

[XmlAttribute] public int Age;<br />

You can control an element or attribute’s name as follows:<br />

public class Person<br />

{<br />

[XmlElement ("FirstName")] public string Name;<br />

[XmlAttribute ("RoughAge")] public int Age;<br />

}<br />

Here’s the result:<br />

<br />

Stacey<br />

<br />

The default XML namespace is blank (unlike the data contract serializer, which uses<br />

the type’s namespace). To specify an XML namespace, [XmlElement] and<br />

[XmlAttribute] both accept a Namespace argument. You can also assign a name and<br />

namespace to the type itself with [XmlRoot]:<br />

[XmlRoot ("Candidate", Namespace = "http://mynamespace/test/")]<br />

public class Person { ... }<br />

This names the person element “Candidate” as well as assigning a namespace to this<br />

element and its children.<br />

XML element order<br />

XmlSerializer writes elements in the order that they’re defined in the class. You can<br />

change this by specifying an Order in the XmlElement attribute:<br />

public class Person<br />

{<br />

[XmlElement (Order = 2)] public string Name;<br />

[XmlElement (Order = 1)] public int Age;<br />

}<br />

If you use Order at all, you must use it throughout.<br />

The deserializer is not fussy about the order of elements—they can appear in any<br />

sequence and the type will properly deserialize.<br />

Subclasses and Child Objects<br />

Subclassing the root type<br />

Suppose your root type has two subclasses as follows:<br />

public class Person { public string Name; }<br />

public class Student : Person { }<br />

public class Teacher : Person { }<br />

XML Serialization | 639<br />

Serialization

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

Saved successfully!

Ooh no, something went wrong!