每个人都在写消极的问题,所以让我们强调一些积极的问题。错误,唯一的积极问题 - 更少(在某些情况下更少)打字。
我编写 GpFluentXMLBuilder 只是因为我讨厌在创建 XML 文档时输入大量代码。不多也不少。
流畅接口的好处是,如果您讨厌这种习惯用法,则不必以流畅的方式使用它们。它们完全可以以传统方式使用。
编辑:“简短和可读性”观点的观点。
我正在调试一些旧代码并偶然发现:
fdsUnreportedMessages.Add(CreateFluentXml
.UTF8
.AddChild('LogEntry')
.AddChild('Time', Now)
.AddSibling('Severity', msg.MsgID)
.AddSibling('Message', msg.MsgData.AsString)
.AsString);
我立即知道代码的作用。但是,如果代码看起来像这样(而且我并没有声称这甚至可以编译,我只是将它放在一起进行演示):
var
xmlData: IXMLNode;
xmlDoc : IXMLDocument;
xmlKey : IXMLNode;
xmlRoot: IXMLNode;
xmlDoc := CreateXMLDoc;
xmlDoc.AppendChild(xmlDoc.CreateProcessingInstruction('xml',
'version="1.0" encoding="UTF-8"'));
xmlRoot := xmlDoc.CreateElement('LogEntry');
xmlDoc.AppendChild(xmlRoot);
xmlKey := xmlDoc.CreateElement('Time');
xmlDoc.AppendChild(xmlKey);
xmlData := xmlDoc.CreateTextNode(FormatDateTime(
'yyyy-mm-dd"T"hh":"mm":"ss.zzz', Now));
xmlKey.AppendChild(xmlData);
xmlKey := xmlDoc.CreateElement('Severity');
xmlDoc.AppendChild(xmlKey);
xmlData := xmlDoc.CreateTextNode(IntToStr(msg.MsgID));
xmlKey.AppendChild(xmlData);
xmlKey := xmlDoc.CreateElement('Message');
xmlDoc.AppendChild(xmlKey);
xmlData := xmlDoc.CreateTextNode(msg.MsgData.AsString);
xmlKey.AppendChild(xmlData);
fdsUnreportedMessages.Add(xmlKey.XML);
我需要相当长的时间(和一杯咖啡)才能理解它的作用。
编辑2:
埃里克格兰奇在评论中提出了一个完全正确的观点。实际上,人们会使用一些 XML 包装器而不是直接使用 DOM。例如,使用 OmniXML 包中的OmniXMLUtils,代码将如下所示:
var
xmlDoc: IXMLDocument;
xmlLog: IXMLNode;
xmlDoc := CreateXMLDoc;
xmlDoc.AppendChild(xmlDoc.CreateProcessingInstruction(
'xml', 'version="1.0" encoding="UTF-8"'));
xmlLog := EnsureNode(xmlDoc, 'LogEntry');
SetNodeTextDateTime(xmlLog, 'Time', Now);
SetNodeTextInt(xmlLog, 'Severity', msg.MsgID);
SetNodeText(xmlLog, 'Message', msg.MsgData.AsString);
fdsUnreportedMessages.Add(XMLSaveToString(xmlDoc));
不过,我更喜欢流利的版本。[而且我从不使用代码格式化程序。]