Study guide

7.2 XMLport Node Hierarchy, Triggers & Stream Manipulation

Microsoft Dynamics 365 Business Central Developer MB-820

Track your progress as you read

Finished sections get a check mark.

1 Chapter 1: Business Central Architecture & Platform Foundation

1.1 Business Central Architecture & Extensions Model 1.2 Customization Lifecycle: Cloud (SaaS) vs. On-Premises 1.3 Base Application, System Application & AppSource

2 Chapter 2: Development Environment & Configuration

2.1: Development Environment Setup: VS Code, AL: Go! Projects & Sandboxes 2.2: AL Configuration Files: app.json & launch.json Parameters 2.3: Multi-Root Workspaces & Project Dependencies

3 Chapter 3: Extension Lifecycle: Debugging, Deployment, Multilanguage & Maintenance

3.1 Debugging & Snapshot Debugging in Visual Studio Code 3.2 Extension Deployment & Schema Synchronization Modes 3.3 Multilanguage Development with XLIFF & Translation Files 3.4 Extension Maintenance, Deprecation & Breaking Changes

4 Chapter 4: Tables, Table Extensions & Data Modeling

4.1: Building Tables, Fields, Keys & Data Types 4.2: Table Extensions & Table Modifications 4.3: FlowFields, FlowFilters & Table Relations 4.4: Enums, Enum Extensions & Extensible Types

5 Chapter 5: Pages, Page Extensions & Role Centers

5.1: Page Types, Anatomy & Control Structure 5.2: Building Card, List & Document Pages 5.3: Page Extensions & Page Customizations 5.4: Role Centers, Headlines & Cue Data Modeling

6 Chapter 6: Reports & Document Generation

6.1 Report Architecture, DataItems & Dataset Design 6.2 Report Layouts: RDLC, Word, Excel & Multilanguage 6.3 Document Reports & Request Page Programming 6.4 Processing-Only Reports & Report Substitutions

7 Chapter 7: XMLports & Data Exchange

7.1 XMLport Architecture, Formats & Properties 7.2 XMLport Node Hierarchy, Triggers & Stream Manipulation

8 Chapter 8: Codeunits, Events, Triggers & Interfaces

8.1 Codeunit Types, Execution & SingleInstance Codeunits 8.2 Events, Publishers, Subscribers & Event Isolation 8.3 Interfaces, Polymorphism & Dynamic Codeunit Invocation 8.4 Installation & Upgrade Codeunits, Data Transfer & Archive

9 Chapter 9: Entitlements, Permissions & Queries

9.1 Permission Sets & Permission Set Extensions 9.2 Inherent Permissions, Inherent Entitlements & Security Scoping 9.3 Query Objects: Joins, Aggregation & Query as Report Data Source

10 Chapter 10: UI Customization, User Assistance & Onboarding

10.1 Profile Objects & Custom Page Views in AL 10.2 User Assistance: ToolTips, Teaching Tips & In-App Tours 10.3 Assisted Setup, Guided Experience & Onboarding Checklists

11 Chapter 11: Business Central Design Patterns & Data Process Model

11.1 Functional Table Types: Master Data, Supplemental & Setup Patterns 11.2 Document Standards: Header, Line, History & Journal Architectures 11.3 Data Process Model & Posting Routine Architecture

12 Chapter 12: AL Language Fundamentals, Data Types & Variables

12.1 AL Syntax, Variable Scope, Primitive & Complex Data Types 12.2 Expressions, Control Flow Statements & Built-in Functions 12.3 Access Modifiers (Public, Internal, Local) & Code Scoping

13 Chapter 13: Data Manipulation, Streams & Error Handling

13.1 Record Operations: Get, FindSet, ModifyAll & Filter Functions 13.2 Streams, File Management & TempBlob 13.3 Error Handling: ErrorInfo, TryFunctions & Collectible Errors

14 Chapter 14: Testing, Test Toolkit & Automation

14.1 Testing Architecture & the Test Toolkit 14.2 Authoring Test Codeunits & UI Handler Functions

15 Chapter 15: Telemetry, Performance Optimization & Analyzers

15.1 Telemetry Configuration & Azure Application Insights 15.2 Custom Telemetry Signals with Session.LogMessage & KQL 15.3 Performance Profiler, SetLoadFields & Query Optimization 15.4 AL Analyzers: CodeCop, AppSourceCop, UICop & PTECop

16 Chapter 16: REST Web Services & JSON in AL

16.1 HttpClient, HttpRequestMessage & REST API Consumption 16.2 JSON Processing: JsonObject, JsonArray, JsonValue & JsonToken

17 Chapter 17: API Pages, OData, Read Scale-Out & OAuth

17.1 API Pages (PageType=API), OData Web Services & REST Endpoints 17.2 Bound and Unbound OData Actions with [ServiceEnabled] 17.3 Read Scale-Out Architecture & DataAccessIntent Configuration 17.4 Microsoft Entra ID App Registrations & OAuth 2.0 Integration

7.2 XMLport Node Hierarchy, Triggers & Stream Manipulation

Key Takeaways Explain This Topic AI

XMLport schema trees are composed of hierarchical nodes: tableelement (bound to table records), fieldelement (bound to table fields), textelement (unbound text variables), and attribute nodes.

Relational parent-child data structures are established using LinkTable and LinkFields properties on nested child tableelements, replicating SQL master-detail joins.

Database write operations during import are controlled by AutoSave, AutoUpdate, AutoReplace, and AutoValidating properties on tableelements.

The XMLport execution lifecycle executes root triggers (OnInitXMLport, OnPreXMLport, OnPostXMLport) and node triggers, enabling runtime flow control via currXMLport.Skip() and currXMLport.Break().

Headless programmatic execution in AL leverages Xmlport.Import and Xmlport.Export with InStream, OutStream, and the TempBlob codeunit for scalable cloud and API integrations.

Last updated: August 2026

7.2 Designing XMLport Nodes, Triggers & Stream Handling in AL

Designing robust XMLports requires a deep understanding of schema node hierarchies, database write mechanics, trigger execution sequences, and programmatic stream manipulation. In complex enterprise integrations, XMLports rarely perform raw table dumps; instead, they transform complex XML payloads, handle master-detail relational structures, apply custom business logic during ingestion, and stream data directly to and from cloud storage or external API endpoints.

1. Schema Node Hierarchy & Element Types

The schema block defines the layout and binding of the data stream. Every XMLport schema begins with a single root textelement , beneath which child nodes are declared. schema

  • {
  • textelement(RootNode)
  • {
  • tableelement(Header; "Sales Header")
  • {
  • AutoSave = true;
  • AutoUpdate = false;
  • AutoReplace = false;
  • fieldelement(DocType; Header."Document Type") { }
  • fieldelement(DocNo; Header."No.") { }
  • fieldattribute(SellToCustomer; Header."Sell-to Customer No.") { }
  • textelement(CalculatedTotal)
  • {
  • trigger OnBeforePassVariable()
  • begin
  • CalculatedTotal := Format(Header."Amount Including VAT");
  • end;
  • }
  • tableelement(Line; "Sales Line")
  • {
  • LinkTable = Header;
  • LinkFields = "Document Type" = field("Document Type"),
  • "Document No." = field("No.");
  • fieldelement(LineNo; Line."Line No.") { }
  • fieldelement(ItemNo; Line."No.") { }
  • fieldelement(Quantity; Line.Quantity) { }
  • fieldelement(UnitPrice; Line."Unit Price") { }
  • }
  • }
  • }
  • }
  • Schema Node Element Types

tableelement : Binds directly to a Business Central table cursor. Represents a repeating record set during import or export.

fieldelement : Binds a schema element directly to a field in the parent tableelement table.

textelement : Declares an unbound string variable within the schema. Used to parse custom XML tags, calculate derived export strings, or hold temporary data for AL trigger processing.

fieldattribute : Used in Format = Xml to serialize a table field as an XML attribute within the parent element's start tag (e.g., <Header SellToCustomer="C10000"> ).

textattribute : Serializes an unbound AL variable as an XML attribute within the parent tag.

Critical tableelement Properties for Data Ingestion

Property Type Default Runtime Ingestion Behavior

AutoSave Boolean true When true , the platform automatically writes the incoming record to the database table. If false , the platform parses fields into the table buffer, but developers must write explicit Rec.Insert(true) or Rec.Modify(true) AL code in node triggers.

AutoUpdate Boolean false When true , if a record with the same primary key already exists during import, the platform updates the existing record with imported values instead of throwing a primary key duplicate error.

AutoReplace Boolean false When true , if an existing record is encountered, the platform deletes or replaces the existing record entirely with the imported record rather than performing an in-place field update.

LinkTable Table Identifier None Specifies the parent tableelement to which this child tableelement is relationally linked.

LinkFields Field Mapping None Specifies the join conditions between child fields and parent fields (e.g., "Document No." = field("No.") ).

MinOccurs Zero / Once Zero Specifies whether the element is optional ( Zero ) or mandatory ( Once ) in incoming XML schemas.

MaxOccurs Once / Unbounded Unbounded Specifies whether the element may repeat ( Unbounded ) or occur at most once ( Once ).

Loading diagram... XMLport Trigger Execution Lifecycle

2. The XMLport Trigger Execution Lifecycle

XMLport triggers execute at precise phases during stream processing. Understanding the sequence of trigger execution is crucial for implementing data transformations, conditional record filtering, and transaction control.

Root-Level Triggers

OnInitXMLport : Executes once when the XMLport object is instantiated before the request page is initialized. Used to set default variable values and establish initial parameters.

OnPreXMLport : Executes after the user dismisses the request page (or immediately upon startup if UseRequestPage = false ), before the first element or stream byte is read/written. Used to initialize file headers, log integration audit entries, or dynamically apply table filters.

OnPostXMLport : Executes once after all records, elements, and streams have been completely processed and written. Used for post-processing routines, sending confirmation telemetry, or cleaning up temporary data.

Node-Level Triggers on tableelement (Import Lifecycle)

OnAfterInitRecord : Fires immediately after a new empty table record buffer is initialized, before incoming field values are mapped. Ideal for populating default header/line values (e.g., setting "Document Type" := "Document Type"::Order ).

OnBeforeInsertRecord : Fires after all fields have been populated and validated, immediately before the platform inserts the record into the database table (when AutoSave = true ). Developers can modify field values or call currXMLport.Skip() to abort insertion of the current record without terminating the entire import batch.

OnAfterInsertRecord : Fires immediately after the record is successfully committed into the table.

OnBeforeModifyRecord : Fires when AutoUpdate = true and an existing record is about to be updated.

OnAfterModifyRecord : Fires after the modified record is updated in the database.

Node-Level Triggers on textelement & textattribute

OnBeforePassVariable (Export): Fires before an unbound text variable or attribute value is written into the export stream. Developers assign the desired formatted string value to the variable in this trigger.

OnAfterPassVariable (Import): Fires immediately after a text variable or attribute is read from the input stream. Developers write custom parsing logic or evaluate the text value to update global variables. // Example: Skipping Invalid Records & Dynamic Parsing in Triggers

  • textelement(TransactionAmountText)
  • {
  • trigger OnAfterPassVariable()
  • var
  • DecValue: Decimal;
  • begin
  • if not Evaluate(DecValue, TransactionAmountText) then
  • currXMLport.Skip(); // Skip invalid line
  • Header."Total Amount" := DecValue;
  • end;
  • }

3. Programmatic XMLport Invocation & Stream Manipulation in AL

In modern cloud architectures, XMLports are rarely triggered by manual user clicks in the UI. Instead, they run programmatically within API handlers, Azure Blob storage synchronization routines, or Job Queue codeunits using InStream and OutStream objects.

  • Core Execution Methods // 1. Interactive or Headless UI Execution
  • Xmlport.Run(Xmlport::"Export Customer CSV", true, false, CustomerRecord);
  • // 2. Headless InStream Ingestion
  • Xmlport.Import(Xmlport::"Import Bank Statement", InStreamVariable);
  • // 3. Headless OutStream Emission
  • Xmlport.Export(Xmlport::"Export PEPPOL Invoice", OutStreamVariable, SalesInvoiceHeaderRecord);
  • In-Memory Streaming Pattern with TempBlob

When exchanging data with web services, Azure Blob Storage, or Base64 payloads, developers use the TempBlob codeunit (from the System Application module) to create transient in-memory streams without creating temporary files on disk. codeunit 50130 "Data Exchange Handler"

  • {
  • procedure ExportCustomersToBlob(var TempBlob: Codeunit "TempBlob"; CustomerPostingGroupFilter: Code[20])
  • var
  • Customer: Record Customer;
  • OutStr: OutStream;
  • begin
  • // Filter customer records
  • if CustomerPostingGroupFilter <> '' then
  • Customer.SetRange("Customer Posting Group", CustomerPostingGroupFilter);
  • // Create OutStream targeting in-memory TempBlob
  • TempBlob.CreateOutStream(OutStr, TextEncoding::UTF8);
  • // Execute XMLport export directly into OutStream
  • Xmlport.Export(Xmlport::"Export Customer CSV", OutStr, Customer);
  • end;
  • procedure ImportVendorsFromStream(InStr: InStream)
  • var
  • VendorXmlport: Xmlport "Import Vendor FlatFile";
  • begin
  • // Set InStream and run import headlessly
  • VendorXmlport.SetSource(InStr);
  • VendorXmlport.Import();
  • end;
  • }
  • Cloud File Handling with DownloadFromStream & UploadIntoStream

In Business Central SaaS (cloud), the server has no direct access to client desktop file systems. All file operations must utilize streams and browser transfer dialogs: procedure ExportAndDownloadCustomerCsv()

  • var
  • TempBlob: Codeunit "TempBlob";
  • InStr: InStream;
  • OutStr: OutStream;
  • FileName: Text;
  • begin
  • FileName := 'Customers_' + Format(Today, 0, '<Year4><Month,2><Day,2>') + '.csv';
  • TempBlob.CreateOutStream(OutStr, TextEncoding::UTF8);
  • // Export XMLport to stream
  • Xmlport.Export(Xmlport::"Export Customer CSV", OutStr);
  • // Convert to InStream and trigger browser download
  • TempBlob.CreateInStream(InStr);
  • DownloadFromStream(InStr, 'Export Data', '', 'All Files (*.*)|*.*', FileName);
  • end;

Exam Watchout — currXMLport.Skip() vs. currXMLport.Break() : Calling currXMLport.Skip() in an import node trigger abandons processing for the current record and advances the stream to the next record. Calling currXMLport.Break() terminates the entire XMLport execution immediately , leaving previously committed records in the database.