Summary

TXmlSerializer is a specialized TSerializer class type for writing values in XML format, using standard VCL XML classes, such as TXmlDocument.

Syntax

TXmlSerializer = class(TSerializer)

Constructors

Properties

 NameDescription
RootValue

Allows to specify XML element name for subsequently serializing root-level value.

Top

Remarks

TXmlSerializer object should be created providing a reference to existing IXMLNode object into which all serializing data will be written. Each root-level data value will be written as a child of provided IXMLNode object. TXmlSerializer creates new IXmlNode for every serializing value using IXmlNode.AddChild method; thus every serializing value will be added as last child of the parent node, respecting ordered nature of  XML documents.

Every element in XML document should have a name (sometimes called "tag"). Since core serializer API does not support root-level values naming, additional API has been provided: NG.Serialization.Xml.TXmlSerializer.RootValue(string) property should be used before actual writing of any root-level value (otherwise, invalid state exception will be thrown):

DelphiCopyCode imageCopy Code
szr.RootValue['MyValue'].Value(7);

Since, NG.Serialization.Xml.TXmlSerializer.RootValue(string) is a default indexed property, its property name can be suppressed to make code more readable:

DelphiCopyCode imageCopy Code
szr['MyValue'].Value(7);

If a value need to be serialized as a root document node, TXmlDocument.Node can be specified as a constructor argument while creating TXmlSerializer object:

DelphiCopyCode imageCopy Code
xml := TXmlDocument.Create(nil);
xml.Active := True;

szr := TXmlSerializer.Create(xml.Node);
try
  srz['Book'].Value<TBook>(book);
finally
  srz.Free;
end;
The above code will result in the following XML:
XmlCopyCode imageCopy Code
<Book>
  <Tittle>Delphi XE Handbook</Tittle>
  <Author>Marco Cantu</Author>
</Book>
However, since xml document allows only single root node, an attempt to write more than one value this way will result in an Xml DOM handling error.

Examples

DelphiCopyCode imageCopy Code
xml         := TXmlDocument.Create(nil);
xml.Options := xml.Options + [doNodeAutoIndent];
xml.Active  := True;
rootNode    := xml.ChildNodes['Books'];

szr := TXmlSerializer.Create(rootNode);
try
  srz['Book'].Value<TBook>(book1);
  srz['Book'].Value<TBook>(book2);
finally
  szr.Free;
end;

xml.SaveToFile('Books.xml');