XMLports for Data Import Export

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 11 read · keep scrolling

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

XMLports for Data Import and Export in AL

Introduction: Why XMLports Matter in Business Central

In the ecosystem of Microsoft Dynamics 365 Business Central, moving data in and out of the system is a constant requirement. Whether you are migrating legacy data, integrating with a third-party warehouse management system, or simply allowing users to export journal entries to Excel for offline analysis, you need a mechanism that is both efficient and reliable. This is where XMLports come into play.

An XMLport is a specialized object in AL (Application Language) designed to handle the transformation of data between the internal Business Central database format and external file formats, primarily XML and CSV (Comma Separated Values). Unlike other methods of data manipulation, such as direct record inserts or using Web Services, XMLports provide a structured, schema-driven approach that manages the mapping of fields, the formatting of data types, and the handling of complex hierarchical relationships.

Understanding XMLports is a critical skill for any Business Central developer. They act as the bridge between your internal business logic and the outside world. By mastering XMLports, you ensure that your data transfers are consistent, repeatable, and maintainable. This lesson will walk you through the architecture, development process, and best practices for creating high-performance XMLports that handle real-world business data with precision.


Not read yet

The Anatomy of an XMLport

An XMLport object consists of two main parts: the definition of the data structure (the schema) and the AL code that triggers logic during the process. When you create an XMLport, you are essentially defining a tree structure that mirrors the file you intend to read or write.

The Schema Designer

In the AL development environment, the schema designer allows you to define nodes. These nodes can be either "Element" or "Attribute."

  • Element nodes are the primary building blocks. They represent tags in XML or columns in a CSV file.
  • Attribute nodes are used specifically in XML to define metadata within an element tag.

For most CSV integrations, you will primarily use Element nodes. The hierarchical nature of the schema allows you to create parent-child relationships, which is essential for documents like Sales Orders where you have a header (the order) and multiple lines (the items being ordered).

Directional Capabilities

XMLports are bi-directional. You can configure them to:

  • Import: Read data from a file and update or insert records in Business Central.
  • Export: Pull data from the database and format it into a file.
  • Both: Create a single object that handles both directions, provided the logic is carefully structured to handle the differences in data flow.

Callout: XMLports vs. RapidStart Configuration Packages While both are used for data migration, they serve different purposes. RapidStart is designed for end-users to perform bulk data loads during implementation. XMLports are developer-centric tools designed to be triggered by code, scheduled tasks, or specific user actions, offering granular control over data validation and business logic execution.


Not read yet

Creating Your First XMLport: A Practical Example

Let’s walk through the creation of a simple XMLport that exports a list of Customers to a CSV file. This is a common requirement for generating reports or preparing data for external communication.

Step 1: Defining the Object

In your AL project, create a new file named CustomerExport.xmlport.al. Use the txmlport snippet to generate the boilerplate code.

xmlport 50100 "Customer Export"
{
    Format = VariableText;
    Direction = Export;
    FieldSeparator = ',';
    TextEncoding = UTF8;

    schema
    {
        textelement(Root)
        {
            tableelement(Customer; Customer)
            {
                fieldelement(No; Customer."No.") { }
                fieldelement(Name; Customer.Name) { }
                fieldelement(City; Customer.City) { }
                fieldelement(Balance; Customer."Balance (LCY)") { }
            }
        }
    }
}

Explanation of the Code

  • Format: By setting Format = VariableText, we tell Business Central to treat this as a CSV file. If you wanted an XML file, you would use Format = Xml.
  • FieldSeparator: This defines what character separates your columns. For standard CSV, a comma is the industry standard.
  • tableelement: This tells the XMLport which database table to iterate over. The XMLport will automatically handle the FindSet and Next logic for you.
  • fieldelement: This maps a specific field in the database table to a column in the file.

Step 2: Triggering the Export

To make this useful, you need to call it from a page or a codeunit. You can trigger the export using the Run method:

var
    CustomerExport: XmlPort "Customer Export";
begin
    CustomerExport.Export();
end;

Note: When using Export(), Business Central will automatically prompt the user to download the generated file via the browser. If you are running this in a background task or an API, you would need to use SetDestination() to point the output to an InStream or OutStream object.


Not read yet

Handling Complex Data: Imports with Validation

Exporting is straightforward, but importing data requires much more care. When importing, you are responsible for ensuring that the data being pushed into Business Central is valid and does not corrupt your system state.

The Import Workflow

When importing, the XMLport follows this sequence:

  1. OnPreXmlPort: Runs before the file is processed. Good for initializations.
  2. OnBeforeInsertRecord: Runs before a record is committed to the database. This is your primary location for validation.
  3. OnAfterInsertRecord: Runs after the record is committed. Useful for logging or updating related tables.

Practical Example: Importing Items

Imagine you need to import item prices from a supplier. You must ensure the Item exists before updating the price.

xmlport 50101 "Item Price Import"
{
    Format = VariableText;
    Direction = Import;
    FieldSeparator = ';';

    schema
    {
        textelement(Root)
        {
            tableelement(Item; Item)
            {
                // We use SourceTableView to filter or restrict access
                fieldelement(No; Item."No.") { }
                fieldelement(Price; Item."Unit Price") { }

                trigger OnBeforeInsertRecord()
                begin
                    // Validation logic here
                    if Item."Unit Price" < 0 then
                        Error('Price cannot be negative for item %1', Item."No.");
                end;
            }
        }
    }
}

Best Practices for Importing

  • Always Validate: Never assume the incoming data is clean. Use the OnBeforeInsertRecord trigger to perform business rule checks.
  • Use Temporary Tables: For complex imports, consider importing data into a temporary table first, performing a batch validation, and then moving the data to the production table.
  • Handle Errors Gracefully: If an error occurs, the entire transaction will roll back. Ensure your logs capture the reason for the failure so the user can fix the input file.

Tip: If you are dealing with large files, avoid putting heavy business logic inside the XMLport triggers. Instead, call a codeunit function that handles the processing in a separate, optimized transaction.


Not read yet

Advanced Features: XMLport Properties and Formatting

Beyond basic imports and exports, XMLports offer several properties that help you control how data looks and feels to the end user.

Controlling File Structure

  • UseRequestPage: Set this to true if you want to show a dialog box to the user before the import/export starts. This is useful for allowing users to select filters or toggle settings (e.g., "Include Headers").
  • FieldDelimiter: Used in CSV files to wrap text values that might contain the separator character (e.g., if a customer name has a comma in it).
  • TextEncoding: Always specify the encoding (usually UTF8 or WINDOWS1252) to avoid character corruption when dealing with international data.

Comparison Table: XML vs. VariableText (CSV)

Feature XML VariableText (CSV)
Structure Hierarchical, nested Flat, tabular
Complexity High (supports complex trees) Low (easy for Excel/Spreadsheet)
File Size Larger (due to tags) Smaller
Human Readable Yes, if formatted Yes
Validation Schema-based (XSD) Manual field mapping

Not read yet

Common Pitfalls and How to Avoid Them

Even experienced developers can run into issues with XMLports. Here are the most frequent mistakes and how to steer clear of them.

1. The "Transaction Loop" Trap

If you perform too many operations inside the OnAfterInsertRecord trigger, you may notice that the import process becomes incredibly slow. This is because every record insertion is treated as a separate database transaction. Solution: Use a batching approach or process large datasets in a background session.

2. Ignoring Encoding

Users often complain that special characters (like symbols or accented letters) look like "gibberish" in the imported file. Solution: Explicitly define the TextEncoding property in your XMLport header. If you are reading files from an external system, ensure you know the encoding they use (usually UTF-8).

3. Missing Field Mappings

If an XMLport is designed to import data but the source file has columns in a different order, the import will fail or map data into the wrong fields. Solution: If the file format is prone to change, avoid relying on positional mapping. For CSVs, always include a header row and use the Import::OnPreXmlPort trigger to validate the header structure before importing the data.

4. Over-reliance on Triggers

Beginners often put too much code in the XMLport object itself. This makes the code hard to unit test and re-use. Solution: Use the XMLport only as a data transport layer. All business logic should reside in dedicated Codeunits. The XMLport should simply call these Codeunits.


Not read yet

Step-by-Step: Implementing a Request Page

A request page allows users to interact with your XMLport. For example, you might want to ask the user if they want to export all customers or only active customers.

  1. Define the Request Page: Inside your XMLport object, add a requestpage block.
  2. Add Variables: Declare variables that will hold the user's choices.
  3. Use the Variables: In the OnPreXmlPort trigger, use those variables to set filters on the table elements.
xmlport 50102 "Filtered Export"
{
    // ... header properties ...
    requestpage
    {
        layout
        {
            area(Content)
            {
                field(OnlyActive; OnlyActive) { Caption = 'Only Active Customers'; }
            }
        }
    }

    trigger OnPreXmlPort()
    begin
        if OnlyActive then
            Customer.SetRange(Blocked, Customer.Blocked::" ");
    end;

    var
        OnlyActive: Boolean;
}

This approach makes your integration much more flexible, as the same XMLport can be used for different business scenarios without changing the underlying code.


Not read yet

Best Practices for Enterprise Integrations

When building XMLports for a production environment, think about maintainability and security.

Security and Permissions

XMLports run with the permissions of the user executing the task. If your integration is meant to be run by a system user (like an API), ensure that the permission sets are correctly assigned. Never assume that the user has full access to every table involved in the XMLport.

Error Logging

Instead of just crashing when an import fails, implement a logging mechanism. Create a custom table called Integration Log and write any errors encountered in the OnBeforeInsertRecord or OnAfterInsertRecord triggers to this table. This allows users to see exactly which row in their CSV file caused the issue.

Performance Considerations

If you are processing tens of thousands of records, consider the following:

  • Minimize Database Hits: Use SetAutoCalcFields to retrieve flow fields in a single query rather than calculating them for every record.
  • Avoid unnecessary triggers: If you don't need to run validation logic on every single field, disable it where possible, though be careful not to bypass mandatory business rules.
  • Use Streams: When dealing with files larger than a few megabytes, always use InStream and OutStream to handle the data flow efficiently without loading the entire file into memory.

Not read yet

Handling Hierarchical Data (The "Header-Line" Problem)

One of the most powerful features of XMLports is their ability to handle parent-child relationships. For example, if you are importing a Sales Order, you have a Sales Header and multiple Sales Lines.

In the XMLport schema, you define this by nesting the tableelement:

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

The LinkTable and LinkFields properties are the keys here. They instruct the XMLport to automatically associate the child records with the correct parent record based on the document number. This is significantly cleaner than writing manual loops to find the correct header for every line in your import file.

Callout: The Power of LinkFields The LinkFields property is essentially an automated SetRange operation. By defining this at the schema level, you allow the Business Central platform to optimize the data retrieval process, ensuring that the XMLport is both faster and less prone to logic errors compared to manual record filtering.


Not read yet

Summary of Key Takeaways

To recap, mastering XMLports is about understanding the balance between structural definitions and procedural logic. Here are the core principles to keep in mind:

  1. Schema-First Design: Always visualize the structure of your file before writing code. Use the hierarchical nature of the schema designer to represent parent-child relationships (like headers and lines) effectively.
  2. Separation of Concerns: Keep your business logic in Codeunits. The XMLport should focus on data mapping and file handling, while the "work" of validating and inserting data should be delegated to the business logic layer.
  3. Robust Validation: Never trust incoming data. Use the OnBeforeInsertRecord trigger to enforce data integrity and prevent system corruption.
  4. User Experience Matters: Utilize Request Pages to provide users with options and filters. A well-designed request page makes your XMLport reusable for multiple business scenarios.
  5. Efficiency and Scaling: For large datasets, leverage InStream/OutStream and optimize database interactions. Avoid performing heavy calculations during the import process.
  6. Error Handling: Implement robust logging. When an import fails, the user should be able to identify exactly which piece of data caused the issue, rather than receiving a generic "error occurred" message.
  7. Security and Permissions: Always test your XMLports with the permission sets that the end-user will actually have. This prevents "Permission Denied" errors that only appear after the code has been deployed to production.

By following these guidelines, you will move from simply "writing code that works" to building robust, professional-grade integrations that stand the test of time. XMLports are a foundational part of the Business Central developer's toolkit, and proficiency with them is a hallmark of a skilled developer who understands the practical realities of business data management.


Not read yet

Frequently Asked Questions (FAQ)

Can I use an XMLport to export data to Excel?

Yes. While you can export to CSV and open it in Excel, you can also set the Format to Xml and use an XSLT transformation to create a native Excel file. However, for most simple reporting needs, exporting to CSV and letting the user open it in Excel is the standard approach.

What happens if the file encoding is wrong?

If the encoding is not specified or set incorrectly, characters outside the standard ASCII range (such as accented letters or currency symbols) will likely be corrupted. Always explicitly set TextEncoding = UTF8 unless you have a specific reason not to.

Is there a limit to the size of the file I can import?

Technically, there is no hard limit on the file size, but there are practical limits imposed by the Business Central server environment (timeouts and memory limits). For very large files (e.g., hundreds of thousands of lines), you should split the file into smaller batches or use a background job queue.

Why does my XMLport import fail silently?

If you are not seeing any errors, it is likely that your logic is not explicitly raising an Error(). If an Error() is not thrown, the system assumes the operation was successful. Always ensure your validation logic includes Error() calls when data does not meet your business requirements.

Can I rename columns in the export file without changing the field names?

Yes. You can use the Name property of the fieldelement to define the tag or column header in the file, while keeping the actual database field name intact. This is useful for creating user-friendly file formats that differ from the internal database nomenclature.

By mastering these concepts, you are well on your way to building sophisticated data interfaces that enhance the functionality of any Business Central implementation. Keep practicing, test your XMLports with various edge cases, and always keep the end-user's experience at the forefront of your design.

Not read yet

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