Thursday, October 8, 2009

Xml Serialization - Control via Attributes

The XmlSerial.pas unit now supports the Attributes. I had to fix a couple of bugs to get it working, just in case you grabbed the copy I posted earlier today.

Now you can use 4 Different attributes to control XML serialization process. Specifically XmlRoot, XmlElement, XmlAttribute, and XmlIgnore. I modified the original class I used in the previous XML serialization post to use these.


[XmlRoot('Person')]
TPerson = class(TObject)
private
FLastName: String;
FBirthday: TDateTime;
FMiddleName: String;
FFirstName: String;
function GetFullName: String;
published
public
[XmlAttribute('First_Name')]
property FirstName : String read FFirstName write FFirstName;
[XmlElement('LAST_NAME')]
property LastName : String read FLastName write FLastName;
[XmlIgnore]
property MiddleName : String read FMiddleName write FMiddleName;
property FullName : String read GetFullName;
property Birthday : TDateTime read FBirthday write FBirthday;
procedure Save(FileName : String);
class function Load(FileName : String) : TPerson;
end;

And now the XML that it outputs and imports is:

<Person First_Name="John">
<LAST_NAME>Doe</LAST_NAME>
<Birthday>34744</Birthday>
</Person>


So basically this mimics the behavior of the same attributes in the XML .NET Serialization. Although, it does not support namespaces yet.

RTTI Article List

2 comments:

  1. Hi, thanks for the nice article.
    Does XMLSerial provide deep serialization ? Meaning, if I have other objects as properties does it serialize the whole object tree ?
    Thank you for your attention,

    ReplyDelete
  2. Yes it does deep serialization.

    ReplyDelete