XML (Xmlite)#
Reading and writing XML through plain Delphi objects: one class per element or type of the schema, one property per child element or attribute. Xmlite is namespace- and schema-aware, and parses in place on the text, without building a DOM.
The classes come from the generator; for a small format without a schema you can write them by hand.
Reading and writing#
uses System.SysUtils,
ProRock.Xmlite,
ProRock.Xmlite.Schema.Order;
var order := TOrderE.Create; // the root element's class: <order> -> TOrderE
try
if order.FromXmlFile('order.xml') then // True when the file was read and parsed
Writeln(order.Customer.Name, ': ', order.Items.Item.Count, ' items');
order.Status := osShipped;
order.ToXmlFile('order.xml');
finally
order.Free;
end;
FromXml and ToXml need ProRock.Xmlite in uses
They come from a class helper, visible only where that unit is listed. Without it: E2003, undeclared identifier.
- Nested objects and lists are created and freed with their parent; just use them. What each schema construct becomes: Generated code.
- A repeating element of a simple type is a list of plain values:
<author>Ann</author><author>Bob</author>isAuthors.Author.Add('Ann'), aTList<T>to use. FromXmlFileandFromXmlBytesread a document in its encoding: the BOM (UTF-8, UTF-16), else the declaration'sencoding=(ISO-8859-1, windows-1252...), else UTF-8.Falsealso when the encoding is unknown or the bytes do not fit it.ToXmlFilewrites UTF-8 without a BOM.FromXmlandToXmltake and give a string, for text you have already.TXmlite.ObjectToXml(obj)writes any object, also one that is not a root element.
Why a read failed: issues#
Each reader has an overload with a TIssues (a record, nothing to free). It says why the read
returned False, with the line and column:
var issues: TIssues;
if not order.FromXmlFile('order.xml', issues) then
Writeln(issues.Text); // Error at line 4, column 1: </order> expected, </ordr> found
- These overloads answer instead of raising: a file that cannot be read is
Falsetoo, its reason inissues. - A read that succeeds lists what is worth knowing: values kept that do not fit their type (warnings), content not in the schema (hints, once a name).
- Each issue has
Severity,Code(stable, for code),WhereandMessage;HasErrorsandfor intoo.OnIssuehears each one as it is added.
Absent or default: presence#
An optional value can be missing from a document, or there with any value - also its default:
<sheet count="0"/> <!-- count is there, and it is 0 -->
<sheet/> <!-- count is absent -->
Both read as Count = 0. Xmlite remembers which values the document had, and writes exactly those back - also when they equal
their default (count="0", FHIR gender value="male", an Excel fill with only defaults). You can ask, mark and remove:
// VIES: in the response, not just the first enum value
if response.Present[@response.TraderNameMatch] then
...
sheet.Count := 0; // set in code and equal to the default: not written...
sheet.SetPresent(@sheet.Count); // ...unless marked present: count="0"
sheet.Clear('Drawing'); // a value or an object: back to its default, and absent
Present[@Obj.X]tells exactly what the writer does: present when read, marked, not the default, or (an object) with any content.[TRequired]values and objects are written always when built in code; read from a document, only when it had them or code sets them.- An assignment in code is not seen (properties write their fields), so a value equal to its default set in code needs
SetPresent. A value that was read stays present when code assigns it the default (Title.XmlValue := ''writes an empty element); to remove it, useClear. @Obj.Xworks for properties that read a field: plain values and required objects. An optional object has a getter (created on first access), so pass its name, the property's or the schema's:SetPresent('Drawing'). A wrong one is skipped, nothing raises: the functions returnFalse.
Content the schema does not describe#
Real documents carry more than their schema: Office writes its own extensions into every file, a newer version of a format adds elements. Xmlite keeps such content and writes it back:
<workbook ...>
<workbookPr defaultThemeVersion="202300"/>
<xr:revisionPtr revIDLastSave="0" documentId="..."/> <!-- not in the schema: kept -->
<bookViews>...</bookViews>
- Attributes without a property are kept in
XmlAttributes. - Elements without a property are kept as their exact text in
XmlUnknownand written back where they were - after the same element, between the same list items. The content ofxs:anyfrom a namespace without generated units is kept the same way. - Values that do not fit their type (
12,50in a decimal,XXXin an enumeration,<amount currency="EUR"/>): the property is not present and holds its default, the read goes on, and the value is written back as it came - an element throughXmlUnknown, an attribute throughXmlAttributes, the text of an element with attributes throughXmlText. Setting the property replaces it; to set it to its default,SetPresenttoo. - Namespace declarations of the document are written back too, so prefixes that only appear in values
(
mc:Ignorable="x14ac") stay declared. Clearremoves the kept content with the rest.
Kept content is never written without being checked: an element whose tags are not closed or crossed, or which uses an
undeclared prefix, fails the read - as any malformed XML does: FromXml returns False, and the object holds what was read
up to there.
ProRock reads on, it does not validate
A value that does not fit is kept and written back, so a document comes through unharmed. The other end will still refuse it, as it would have refused the document before.
Mixed content and element order#
<p><b>status</b>: final <span>(Details)</span></p>
Text between child elements, as in HTML - or a FHIR resource's narrative, which is XHTML.
- A mixed type (
mixed="true") gets[TMixed]: its object keeps the text runs and its children in document order inXmlContent. - A repeating choice (
<font>in Excel styles:<sz/><color/><name/>in any order) gets[TOrdered]: the same order, without text.
The typed lists stay as they are - p.B[0] is the first <b> - and XmlContent refers to the same objects:
Writeln(obs.Text.&Div.InnerText); // all the text, children included, in document order
for var item in p.XmlContent do
if item.IsText then
Write(item.Text)
else if item.IsElement<TAE> then
Write('[', item.Element.InnerText, '](', item.ElementAs<TAE>.Href, ')')
else
Write(item.Element.InnerText); // item.Name: the element's name - b, span
Built in code, in the order of the calls:
var p := obs.Text.&Div.Add<TPE>; // added to Div.P and to the order
p.Add<TBE>.AddText('status');
p.AddText(': final');
// <div xmlns="http://www.w3.org/1999/xhtml"><p><b>status</b>: final</p></div>
XmlTextof a mixed element is its leading text (cp:keywords: the whole text); setting it replaces that text.- Children added straight to a typed list are written after the ones in
XmlContent, in the schema's order. XmlContentis read-only. Remove a child withRemove(child): it leaves both its list andXmlContent; one deleted, extracted or cleared through its list leavesXmlContenttoo. A plain value deleted from its list moves the places of the values after it.- Inside a mixed element the writer writes no indentation (
Pretty): it would become a part of the text. OrderedandMixedare settings of the class's metadata (TPE.Meta.Xmlite.Mixed) - changeable at run time, for every object of the class. Units generated before 1.6 have no[TMixed]: regenerate them.
Derived types: xsi:type#
When the schema allows a derived type in place of the declared one, the document says so with xsi:type. To write it, tell the
element which class it holds:
props.Modified.SetXsiType(TW3cdtfCT); // <dcterms:modified xsi:type="dcterms:W3CDTF">
SetXsiType refuses a class that is not a complex type derived from the element's type. See
XML concepts for what this means.
What of XML and XML Schema is covered: XML support; notes for using it: Limitations and notes.