Using XMLports in AL Code

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 12 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Mastering XMLports in AL Development

Introduction: The Gateway to Data Integration

In the modern enterprise resource planning (ERP) ecosystem, the ability to move data in and out of a system is not just a luxury; it is a fundamental requirement. Whether you are migrating data from a legacy system, integrating with a third-party web service, or providing a mechanism for users to export data for external reporting, you need a reliable, structured, and efficient way to handle these tasks. In the world of AL (Application Language) development for Business Central, the XMLport object is the primary tool designed specifically for this purpose.

XMLports are unique objects that bridge the gap between the structured internal database tables and the external world of XML, CSV, and fixed-width text files. Unlike other objects that might focus purely on logic or UI, an XMLport acts as a translator. It defines how data should be structured during an import or an export, mapping the fields of your Business Central tables to the nodes of an XML file or the columns of a flat file. Understanding how to design, configure, and code these objects is a core competency for any AL developer who wants to build truly interconnected applications.

This lesson explores the anatomy of XMLports, how they handle different data formats, and the best practices for implementing them in your projects. By the end of this guide, you will be able to confidently build integration points that are both performant and maintainable, ensuring that your data flows exactly where it needs to go without unnecessary friction.


Not read yet

The Anatomy of an XMLport

An XMLport is defined by its structure, which is essentially a hierarchical schema. When you create an XMLport, you are defining a tree-like structure where elements represent the data points, and attributes or values represent the actual content. This structure is mapped directly to table fields or variables within your AL code.

The Basic Structure

At the top level of every XMLport, you have the XMLport definition block. Inside this block, you define the Schema section, which acts as the blueprint for your file. The schema is organized into elements, which can be either data elements (linked to a table) or field elements (linked to specific fields within that table).

Consider the following core components of an XMLport:

  • Direction: You must define whether the XMLport is for importing, exporting, or both.
  • Format: You can choose between XML, Variable Text (CSV), or Fixed Text.
  • Table Elements: These define the root or parent nodes in your schema, usually tied to a specific table in Business Central.
  • Field Elements: These are the individual data points that map to table fields.

Callout: XMLport vs. RapidStart While RapidStart is excellent for initial data migration and bulk configuration, XMLports are designed for programmatic, repeatable data integration. Use RapidStart for the "one-time" setup of a new company, but use XMLports when you need to build custom integrations that run on a schedule or are triggered by specific user actions within the application.


Not read yet

Configuring XMLport Formats

One of the most powerful features of XMLports is their flexibility regarding the output format. You are not restricted to XML. In many business scenarios, particularly when dealing with legacy banks or third-party logistics providers, you will be required to produce or consume flat files like CSV or fixed-width text.

Working with XML

XML is the native format for XMLports. When you define your schema, the AL compiler generates the necessary code to handle the hierarchical structure. You can define attributes for XML elements, which is a common requirement for web services.

Working with Variable Text (CSV)

For CSV files, the XMLport handles the delimiters, quotes, and field separators automatically. You simply define the fields in the order they should appear in the file. The XMLport automatically handles the conversion of data types (e.g., Dates to string formats, Decimals to localized number formats).

Working with Fixed Width

Fixed-width files are common in mainframe integrations. Here, you must specify the length of each field in the XMLport property. If a field is shorter than the defined length, the system automatically pads the remaining space with the character of your choice.

Tip: Handling Character Encoding Always verify the expected character encoding of the external system. XMLports generally default to UTF-8, but some legacy systems may require specific encodings like Windows-1252. You can control this via the Encoding property in the XMLport designer.


Not read yet

Step-by-Step: Creating Your First XMLport

Let’s walk through the creation of a simple XMLport that exports Customer data to a CSV file.

  1. Define the XMLport Object: Create a new file with the extension .al and define the object structure.

    xmlport 50100 "Export Customers"
    {
        Direction = Export;
        Format = VariableText;
        TextEncoding = UTF8;
        UseRequestPage = false;
        
        Schema
        {
            textelement(Root)
            {
                tableelement(Customer; Customer)
                {
                    fieldelement(No; Customer."No.") { }
                    fieldelement(Name; Customer.Name) { }
                    fieldelement(Balance; Customer."Balance (LCY)") { }
                }
            }
        }
    }
    
  2. Configuring the Properties: Note the Direction property set to Export. If you wanted to allow both, you would set it to Both. The Format is set to VariableText, which tells the system to use the default field separator (usually a comma).

  3. Executing the XMLport: To trigger this XMLport from a page or a codeunit, you use the Xmlport.Run() function.

    procedure ExportData()
    var
        ExportCustomers: Xmlport "Export Customers";
    begin
        ExportCustomers.Export();
    end;
    

Understanding the Schema Hierarchy

The textelement acts as a wrapper. In a CSV file, this might not be strictly necessary, but it provides a clean structure. The tableelement is the engine of the XMLport. It tells the system to iterate through the Customer table. For every record it finds, it will print the fields defined in the fieldelement blocks.


Not read yet

Advanced XMLport Techniques: Triggers and Logic

While simple mappings are useful, real-world scenarios often require data transformation or validation during the import/export process. XMLports provide a series of triggers that allow you to inject custom AL code at specific points in the lifecycle of the data operation.

Key XMLport Triggers

  • OnPreXmlPort: Runs before the XMLport starts processing. This is the perfect place to set filters or perform initial setup.
  • OnPostXmlPort: Runs after the processing is complete. Use this for cleanup or to notify the user.
  • OnBeforeInsertRecord: Specifically for imports. This trigger runs before the record is written to the database. You can use this to perform data validation or modify values before they are committed.
  • OnAfterInitRecord: Runs after a record has been initialized (but before fields are populated). Useful for setting default values.

Practical Example: Validating Imports

Suppose you are importing Sales Orders, and you need to ensure that the customer exists and is not blocked before the record is inserted.

xmlport 50101 "Import Sales Orders"
{
    Direction = Import;
    Format = Xml;

    Schema
    {
        tableelement(SalesHeader; "Sales Header")
        {
            trigger OnBeforeInsertRecord()
            var
                Customer: Record Customer;
            begin
                if Customer.Get(SalesHeader."Sell-to Customer No.") then begin
                    if Customer.Blocked = Customer.Blocked::All then
                        Error('Customer %1 is blocked for all transactions.', Customer."No.");
                end;
            end;
        }
    }
}

Warning: Performance Pitfalls Be careful with code inside OnBeforeInsertRecord. Since this trigger runs for every single record being imported, any complex lookup or heavy calculation will significantly slow down the entire process. Keep your logic as lightweight as possible. If you need to perform heavy data validation, consider importing into a staging table first and then processing the data in a batch job.


Not read yet

Handling Complex Data Structures

Sometimes your data is not a flat list. You might have a header record with multiple lines (e.g., a Sales Header with multiple Sales Lines). XMLports handle this nesting perfectly by nesting the tableelement blocks within each other.

Nested Table Elements

When you nest a tableelement inside another, the XMLport automatically maintains the parent-child relationship. If you are importing an XML file, the XMLport will look for the child nodes within the parent node. If you are exporting, it will iterate through the lines for every header it finds.

tableelement(SalesHeader; "Sales Header")
{
    fieldelement(No; SalesHeader."No.") { }
    
    tableelement(SalesLine; "Sales Line")
    {
        LinkTable = SalesHeader;
        LinkFields = "Document No." = field("No.");
        
        fieldelement(Item; SalesLine."No.") { }
        fieldelement(Qty; SalesLine.Quantity) { }
    }
}

This structure is highly efficient. By defining the LinkTable and LinkFields, you tell the XMLport exactly how to relate the two tables, ensuring that the exported file maintains the correct hierarchy.


Not read yet

Best Practices for XMLport Development

To ensure your integrations are robust and maintainable, follow these industry-standard practices:

  1. Use Request Pages: Always set UseRequestPage = true if you want to allow users to set filters or change the file path dynamically before the export starts.
  2. Encapsulate Logic: Do not put too much business logic inside the XMLport triggers. Instead, call functions in a dedicated Codeunit. This makes your code easier to unit test and reuse.
  3. Handle Errors Gracefully: When importing data, use try-catch blocks or validation checks to ensure that one bad record doesn't crash the entire import job.
  4. Keep it Simple: If an XMLport becomes too complex, consider splitting it into smaller, more focused objects. A single XMLport should ideally handle one specific type of data entity.
  5. Documentation: Always add comments explaining the expected format of the incoming/outgoing file, especially if you are using fixed-width or CSV formats where column order is critical.
Feature XML Format Variable Text (CSV) Fixed Width
Hierarchy Nested Flat Flat
Readability High Medium Low
Performance Moderate High High
Complexity High Low Moderate

Not read yet

Common Pitfalls and How to Avoid Them

Even experienced developers run into issues with XMLports. Being aware of these common traps will save you hours of debugging.

Trap 1: Hardcoding File Paths

Never hardcode file paths like C:\Temp\file.csv. Business Central runs in the cloud (SaaS), and it does not have direct access to your local C drive. Always use the File Management codeunit to handle streams or blob storage.

Trap 2: Ignoring Data Types

The XMLport does a lot of heavy lifting for you, but it can struggle with complex data types like Option fields or Blob fields. Always test how your XMLport handles these fields, and use OnAfterInitRecord to perform manual conversions if necessary.

Trap 3: Not Using Source Variables

If you are performing an import, you often don't want to write directly to the production table. Using a temporary table as the source for your tableelement allows you to validate the data, transform it, and then move it to the actual table in a controlled manner.

Note: Using Temporary Tables You can set the SourceTableTemporary property to true on your table elements. This is an excellent way to perform "what-if" analysis or to stage data before committing it to the permanent database.


Not read yet

Detailed Example: A Complete Integration Scenario

To solidify your understanding, let's build a scenario where we import a CSV file containing employee hours for a timesheet application.

The Requirements

  • Input: A CSV file with columns: EmployeeNo, Date, Hours, ProjectCode.
  • Logic: Validate the Employee exists and the date is not in the future.
  • Action: Insert into a custom table Time Entry.

The Implementation

xmlport 50102 "Import Timesheets"
{
    Direction = Import;
    Format = VariableText;
    FieldDelimiter = '<,>';
    FieldSeparator = '<;>';

    Schema
    {
        textelement(Root)
        {
            tableelement(TimeEntry; "Time Entry")
            {
                fieldelement(Emp; TimeEntry."Employee No.") { }
                fieldelement(Date; TimeEntry.Date) { }
                fieldelement(Hours; TimeEntry.Hours) { }
                fieldelement(Project; TimeEntry."Project Code") { }

                trigger OnBeforeInsertRecord()
                var
                    Emp: Record Employee;
                begin
                    if not Emp.Get(TimeEntry."Employee No.") then
                        Error('Employee %1 not found.', TimeEntry."Employee No.");
                    
                    if TimeEntry.Date > Today then
                        Error('Date cannot be in the future.');
                end;
            }
        }
    }
}

Why this works:

  • Delimiter Configuration: By specifying FieldDelimiter and FieldSeparator, you ensure the XMLport is compatible with the specific CSV format provided by the client.
  • Validation: The OnBeforeInsertRecord trigger acts as a gatekeeper, ensuring only valid data reaches your Time Entry table.
  • Clarity: The code is readable, modular, and directly maps the file columns to the table fields.

Not read yet

Advanced Troubleshooting Techniques

When an XMLport fails, it can sometimes be difficult to pinpoint exactly where the error occurred. Here are some strategies to debug effectively:

  1. The "Message" Debugger: Temporarily add Message() calls in your triggers to output the value of fields as they are being processed. This helps you identify exactly which record is causing an error.
  2. Review the Event Log: Business Central logs errors in the Telemetry section. If you are working in a SaaS environment, check the Application Insights telemetry to see detailed error messages that might not be displayed in the UI.
  3. Validate the File: If you are importing, try opening the file in a text editor to ensure there are no hidden characters, unexpected line breaks, or encoding issues that might be confusing the XMLport parser.
  4. Test with Small Samples: Never test with a massive file. Always start with a file containing 1-2 records. Once the logic is sound, you can scale up to larger datasets.

Not read yet

Summary of Key Takeaways

XMLports are an indispensable part of your AL toolkit. They provide a structured, efficient way to handle data exchange, ensuring that your Business Central environment remains connected to the broader business ecosystem. As you continue your development journey, keep these points in mind:

  • Understand the Format: Always clarify whether you are working with XML, CSV, or Fixed-Width files before you start, as this dictates your configuration strategy.
  • Leverage Triggers: Use OnBeforeInsertRecord and OnAfterInitRecord to perform essential validation and data transformation, but keep logic simple to maintain performance.
  • Use Hierarchy Wisely: Nest your table elements correctly to handle parent-child relationships, but keep the schema as flat as possible to reduce complexity.
  • Prioritize Security and Validation: Never trust incoming data. Always validate data in the import triggers to prevent corrupting your database with invalid information.
  • Think About Reusability: Design your XMLports to be modular. If you find yourself writing the same validation logic in multiple XMLports, move that logic to a central codeunit.
  • Monitor Performance: Large imports can be resource-intensive. Always test with realistic data volumes and consider batching or background processing if you are dealing with thousands of records.
  • Embrace the Request Page: Providing users with a request page makes your XMLports more versatile, allowing them to filter, sort, and refine the data they are importing or exporting without needing code changes.

By mastering these concepts, you transition from simply "writing code" to "designing solutions." XMLports are not just about moving data; they are about creating reliable, automated processes that keep the business running smoothly. Take the time to practice these techniques, experiment with different properties, and always keep the end-user's workflow in mind.


Not read yet

Frequently Asked Questions (FAQ)

Q: Can I use XMLports to interact with Web Services directly? A: While XMLports can generate or consume XML, they are primarily designed for file-based operations. For real-time web service communication, you should use HttpClient and the Json object types in AL. XMLports are best for bulk data exchange via files.

Q: What happens if the file format changes? A: If the file format changes (e.g., a new column is added), you will need to update the XMLport schema. This is why it is critical to document the expected format of your files. If you anticipate frequent changes, consider using an intermediate staging table or a more flexible integration approach.

Q: Are XMLports compatible with all Business Central versions? A: Yes, XMLports have been a staple of the platform for a long time. However, ensure you are using the modern AL development environment (Visual Studio Code) rather than the legacy C/SIDE environment to take advantage of the latest language features and performance improvements.

Q: How do I handle large exports that time out? A: If an export takes too long and hits the server timeout, consider running the XMLport as a background task or a job queue entry. This allows the process to run asynchronously without blocking the user's interface.

Q: Can I use an XMLport to update existing records instead of creating new ones? A: Yes. In the tableelement, you can set the AutoUpdate property to true. This tells the XMLport to search for an existing record based on the primary key and update it if it exists, rather than attempting to insert a duplicate.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.