Technical Article

XFA SOM Path Expressions in Delphi: Dynamic Form Data

On a receipt with three line items, $data..Total_Price[1] comes back as an empty string, even though three Total_Price values sit right there in the datasets packet. Anyone who reads .. the way XPath or a shell reads it expects a step up to the parent. In an XFA SOM expression it is a descendant search, and the [1] after it counts siblings under whichever parent held the first hit — and a single Detail row only has one price. The path that works is $data.Receipt.Detail[1].Total_Price, or Detail[*] when you want every row

That mismatch only bites once a form stops being flat. A VAT return or customs declaration built as a dynamic XFA form does not carry twelve fields named Total_Price_1 through Total_Price_12. It declares one Detail subform in the template and lets the data decide how many times it appears. The values live in a second tree, the Data DOM inside the datasets packet, where each line item is another <Detail> element under <Receipt>. A flat field name has no way to say "the price on the third line" or "every line over 200". The Scripting Object Model chapter of the Adobe XFA 3.3 specification defines SOM expressions for exactly that job, and they borrow just enough punctuation from XPath and file paths to mislead

PDF Library for Delphi: This diagram contrasts an XFA template DOM that declares a Detail subform once with the Data DOM that repeats it for every arriving data record
A dynamic XFA form declares each subform once in the template and repeats it in the datasets packet as data arrives

Roots, delimiters and zero-based indexes in TPDFlib XFA paths

In PDF Library for Delphi, TPDFlib.GetXFAFormFieldValue and TPDFlib.SetXFAFormFieldValue take a SOM path into the datasets packet, and the root can be spelled several ways that all land on the same node. $data is the XFA 3.3 short form of xfa.datasets.data; !data is the short form rooted at xfa.datasets; a bare relative path such as Receipt.Tax starts at the data node too. $record resolves to the outer data record — the first element under the data node — which is how XFA 3.3 defines it for packets that do not use record processing. Template-side calls such as SetXFAFormFieldAccess accept $template and xfa.template in the same spirit

Segments may be dot-delimited or slash-delimited. The rule that decides between them is blunt: if the path contains a slash anywhere, every period in it is an ordinary character, so $data/Receipt/Line.Item addresses an element literally named Line.Item. In a dot-delimited path you escape the same period as Line\.Item. Occurrence indexes are zero-based per the specification, so Detail[0] is the first row — one more place where XPath habits (which count from 1) produce an off-by-one. Business data that carries its own namespace prefix is matched by local name, and <m:Receipt> still answers to Receipt

PDF Library for Delphi: This diagram dissects a SOM path expression over XFA datasets, labeling the dataset root, delimited segments, a zero-based occurrence index and the targeted leaf value
Roots, delimiters and zero-based occurrence indexes compose into SOM paths, with several spellings resolving to the same node

One detail about return values matters before any batch job. SetXFAFormFieldValue returns 1 when the document has a datasets packet it can edit; a path that matches no node writes nothing and still returns 1. The library treats a SOM path like a query, and an empty result set is a legal answer. So the check worth adding is a read of the target row before the write, as below

uses
  System.SysUtils, PDFlibrary;

var
  Lib: TPDFlib;
  Tax: WideString;
begin
  Lib := TPDFlib.Create;
  try
    Lib.LoadFromFile('vat-return.pdf', '');

    // Four spellings, one data node
    Tax := Lib.GetXFAFormFieldValue('Receipt.Tax');
    Tax := Lib.GetXFAFormFieldValue('$data.Receipt.Tax');
    Tax := Lib.GetXFAFormFieldValue('xfa.datasets.data.Receipt.Tax');
    Tax := Lib.GetXFAFormFieldValue('$record.Tax');

    // Guard you add yourself: reading the row group returns its child
    // values joined, so an empty result means the row is missing or blank
    if Lib.GetXFAFormFieldValue('$record/Detail[0]') = '' then
      raise Exception.Create('Detail[0] not found in datasets');

    // Slash form, zero-based index: the first line item
    Lib.SetXFAFormFieldValue('$record/Detail[0]/Total_Price', '251.00');
    Lib.SaveToFile('vat-return-updated.pdf');
  finally
    Lib.Free;
  end;
end;

How do you fill every repeating row in one call?

Put [*] on the repeating element. Where a numeric index picks one sibling, [*] picks all same-name siblings, so $data.Receipt.Detail[*].Surcharge reaches the surcharge on every line item. SetXFAFormFieldValue writes the same value into each match. GetXFAFormFieldValue returns the matches joined with |, so two rows priced 250.00 and 60.00 come back as 250.00|60.00

That joined string is fine for display and bad for arithmetic. A data node with no text contributes nothing to the join — no empty slot, no extra separator — so three rows where the middle price is blank read back as 250.00|60.00, and splitting on | pairs the second price with the wrong line. A value that itself contains a pipe breaks the split as well. My preference is firm here: use [*] for writes, and walk explicit indexes for any read that feeds a calculation

GetXFAFormFieldNames will not give you those indexes. It returns slash-delimited leaf paths with namespace prefixes dropped, scanning every top-level record, and a repeated row never carries an [n]. When a row holds several leaves, each row lists Receipt/Detail/Total_Price again; when consecutive rows produce identical paths back to back, they collapse into a single entry, so the list does not even tell you how many rows there are. Feed that string straight back into GetXFAFormFieldValue and you read row 0, every time

var
  Lib: TPDFlib;
  Names, Price: WideString;
  Row: Integer;
  Total: Double;
  FS: TFormatSettings;
begin
  FS := TFormatSettings.Create;
  FS.DecimalSeparator := '.';
  Lib := TPDFlib.Create;
  try
    Lib.LoadFromFile('invoice.pdf', '');

    // Leaf paths, one per line; repeated rows repeat the path without [n]
    Names := Lib.GetXFAFormFieldNames(#13#10);

    // One call stamps the column on every Detail row
    Lib.SetXFAFormFieldValue('$data.Receipt.Detail[*].Surcharge', '0.00');

    // Read with explicit indexes so a blank price keeps its row.
    // Assumes each Detail row carries a Surcharge element: after the
    // write above, the group read is non-empty for every existing row
    Total := 0;
    Row := 0;
    while Lib.GetXFAFormFieldValue(
      Format('$data.Receipt.Detail[%d]', [Row])) <> '' do
    begin
      Price := Lib.GetXFAFormFieldValue(
        Format('$data.Receipt.Detail[%d].Total_Price', [Row]));
      if Price <> '' then
        Total := Total + StrToFloat(Price, FS);
      Inc(Row);
    end;

    Lib.SaveToFile('invoice-updated.pdf');
  finally
    Lib.Free;
  end;
end;

Writes have one twist of their own. When the target node holds child elements rather than text — the shape a multi-select list box uses in the Data DOM — SetXFAFormFieldValue treats | in the new value as an item separator and rebuilds one child per item. Writing 'A|B' into such a node produces two entries, which is what a list box wants and a surprise anywhere else

Descendant, child-wildcard and parent steps

Three structural selectors cover the cases where you know a field name but not its depth, and each one means something different from its XPath look-alike. The descendant selector .. matches at any depth: $data..Total_Price finds the first Total_Price anywhere under the data root, and a write through that path updates only that first node. An occurrence index after a descendant match stays inside the branch where the match lives, which is the empty string from the opening paragraph

The child wildcard .* matches every direct child and lets the remaining segments filter. $data.Receipt.*.Total_Price reaches the Total_Price inside each child branch of Receipt and skips a same-name summary field sitting directly on Receipt — handy when the form keeps a grand total under the same tag as the line prices. The parent property is the real one-level climb, and XFA 3.3 keeps it apart from .. on purpose: $data.Receipt.Detail[1].parent.Tax starts at the second line item, steps up to Receipt and lands on its Tax value

The library resolves all of these with its own XML parser and path evaluator rather than MSXML, so the same path gives the same answer on Windows, Linux, macOS and under Free Pascal. For a batch job that fills agency forms on a Linux server, that matters more than any single selector

Filtering rows with #dataGroup, #dataValue and predicates

When names are the problem, address nodes by class. The #class syntax picks Data DOM nodes by kind, which is the practical route when XML tags contain characters that are awkward to spell in a script name. #dataGroup matches elements that have element children and #dataValue matches leaf elements, and both take numeric or [*] occurrences: $data.Receipt.#dataGroup[0].#dataValue[0] is the first value inside the first group under Receipt

When content is the filter, use a predicate. .[expression] keeps the same-name siblings whose child value passes one comparison of the form child op literal, with >, <, >=, <=, =, == or !=. A .rawValue suffix on the left side, the way FormCalc scripts usually write it, is accepted. The predicate is evaluated as a data filter and does not run FormCalc or JavaScript, so a function call such as contains(...) or an and/or combination selects nothing. Reads come back |-joined when several rows match; writes update every match

PDF Library for Delphi: This diagram surveys six structural SOM selectors for repeated XFA data: the occurrence wildcard, descendant lookup, child wildcard, parent step, class selectors and content predicates
Wildcards, descendants, parent steps, class selectors and content predicates each cover a different addressing gap

The period causes trouble again. In a dot-delimited path, [Total_Price > 200.50] is cut in half at the decimal point, and so is Total_Price.rawValue. Write predicates with decimals or .rawValue in slash form, or escape the period

// Flag every line whose price exceeds 200
Lib.SetXFAFormFieldValue(
  '$data.Receipt.Detail.[Total_Price > 200].Review_Flag', '1');

// Decimal literal: slash form keeps 200.50 in one piece...
Desc := Lib.GetXFAFormFieldValue(
  '$data/Receipt/Detail/[Total_Price > 200.50]/Description');
// ...or escape the period in the dot form
Desc := Lib.GetXFAFormFieldValue(
  '$data.Receipt.Detail.[Total_Price > 200\.50].Description');

// FormCalc-style .rawValue on the left, slash form
Desc := Lib.GetXFAFormFieldValue(
  '$data/Receipt/Detail/[Total_Price.rawValue <= 200]/Description');

// String equality compares text exactly
Lines := Lib.GetXFAFormFieldValue(
  '$data.Receipt.Detail.[Currency = ''EUR''].Description');

// Class-based addressing when tag names resist script spelling
Total := Lib.GetXFAFormFieldValue(
  '$data.Receipt.#dataGroup[0].#dataValue[0]');

Relational operators parse both sides as numbers with a period as the decimal separator, whatever the regional settings on the machine running the job. A data value that does not parse that way drops out of the comparison entirely. Suppose a form stores one price as 1,250.00 and another as 250,00 (the German habit): neither row matches > 200, and neither matches <= 200. The equality operators compare text, so [Qty = 1] does not match a row holding 1.0. If a predicate returns fewer rows than you expect, read the raw column with Detail[*] and look at how the values are written

When a path is not enough: rewriting the packet

For anything a single path cannot express, drop to the packet. GetXFAToString returns the whole XDP as XML, and SetXFAFromString installs a complete packet — template and datasets together — under /AcroForm/XFA, creating the AcroForm container when the document has none and raising the file to PDF 1.5 or later. It decodes UTF-8 packets and UTF-16 packets with or without a byte-order mark, so an agency file can be passed through byte for byte. In PDF/X mode it returns 0 and leaves the document untouched

The packet route is also where the scope of path addressing points you. $record follows the non-record-processing definition, so dataWindow paging and record-group rotation are handled by editing the XML yourself. Paths resolve against the datasets and template trees as they sit in the packet, not the merged Form DOM a viewer builds at run time, and they address elements; attributes in the data stay attributes and are edited at packet level. A common production shape keeps the agency-issued XDP on disk, installs it, then runs a handful of SOM writes for the per-invoice values:

// Helper you write yourself: raw bytes in, no code-page conversion
function ReadRawFile(const FileName: string): AnsiString;
var
  Stream: TFileStream;
begin
  Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
  try
    SetLength(Result, Stream.Size);
    if Stream.Size > 0 then
      Stream.ReadBuffer(Result[1], Stream.Size);
  finally
    Stream.Free;
  end;
end;

procedure FillReturn(Lib: TPDFlib; const InvoiceNo, Total: WideString);
begin
  // Options is reserved; pass 0. Returns 0 in PDF/X mode
  if Lib.SetXFAFromString(ReadRawFile('vat-return-2026.xdp'), 0) <> 1 then
    raise Exception.Create('XFA packet was not installed');
  Lib.SetXFAFormFieldValue('$data.Receipt.InvoiceNo', InvoiceNo);
  Lib.SetXFAFormFieldValue('$data.Receipt.Total', Total);
  Lib.SetXFAFormFieldValue('$data.Receipt.Detail[*].Surcharge', '0.00');
end;

ISO 32000-2 deprecates XFA, and for a form you design yourself the classic AcroForm model is the better bet; it has its own automation story in the article on interactive form actions and JavaScript. SOM addressing earns its keep on the forms you are handed and cannot redesign. To move whole data sets between files instead of addressing nodes one path at a time, see FDF, XFDF and XFA form data interchange

The XFA value, enumeration and packet functions used above are part of PDF Library for Delphi, which is also callable from C# and VB.NET; its reference pages list every form-handling call with parameters and return codes