Tuesday, October 06, 2009

Fluent XML [3]

Few days ago I was answering some OmniXML related question on Slovenian Delphi forum and I tried using GpFluentXML to provide the answer. The emphasis is on “tried” – my unit was just not powerful enough to be useful in this case.

So what else could I do besides improving GpFluentXML?

Modifications were very small. I added two overloads (AddChild and AddSibling) which allow setting node value. Implementation is equally trivial as everything else inside the fluent XML unit.

function TGpFluentXmlBuilder.AddChild(const name: XmlString;
value: Variant): IGpFluentXmlBuilder;
begin
Result := AddChild(name);
SetTextChild(fxbActiveNode, XMLVariantToStr(value));
end; { TGpFluentXmlBuilder.AddChild }

(And similar for AddSibling.)

Now I (and you and everybody else) can write such code:

var
data : TData;
xmlBuilder: IGpFluentXmlBuilder;
begin
xmlBuilder := CreateFluentXml
.AddProcessingInstruction('xml', 'version="1.0" encoding="UTF-8"')
.AddChild('DataTransfer')
['xsi:noNamespaceSchemaLocation', 'http://www.tempuri/schema.xsd']
['xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance']
.AddChild('Dokument');
for data in GetData do begin
xmlBuilder
.Mark
.AddChild('ID', data.ID)
.AddSibling(DocumentInfo')
.AddChild('GeneratedBy', data.Originator)
.AddSibling('Title', data.Title)
.Return;
end;
end;

A non-obvious trick – .Mark and .Return are used inside the loop to store/restore proper level at which the child nodes must be inserted.

Full GpFluentXML source is available at http://17slon.com/blogs/gabr/files/GpFluentXml.pas.

5 comments:

  1. I like it very much!
    Thanks,
    Ajasja

    ReplyDelete
  2. What is tdata type?

    ReplyDelete
  3. @Brad: Some class/record. I was just using it to simplify the code. In my case it has three properties: ID, Originator and Title.

    ReplyDelete
  4. Thank you, I looked at delphi.si and deciphered what it did.

    Thank you for the demo code!

    ReplyDelete
  5. Hello gabr,

    Needed to build some big-ass XML documents this week. Already have a DOM library due to other needs in my code (XMLBlackbox from EldoS software) so I ported it. It took me a whole ten minutes to make it work - I had to use classes instead of interfaces in several places, but it did the trick.

    Thank you very much!

    ReplyDelete