Mail Merge with XML Data Source

You can use a variety of data sources when performing a Mail Merge operation, including an XML file. XML can store repeating records and parent-child relationships. In C++, parse the file and implement IMailMergeDataSource to provide those records to Aspose.Words.

Advantages of XML As a Data Source

XML data sources are useful for storing data without the overhead of a database. They are useful for offline applications where users need to add, edit, and delete data when they cannot connect to a database.

Since XML stores data in plain text format, the storage is platform-independent. Thus, data can be exported, imported, or moved between applications.

Fill a Merge Template from XML

The following XML contains the data needed to fill a merge template. Download Mail merge data - Customers.xml and place it in MyDir, the examples’ data directory.

<?xml version="1.0" encoding="utf-8"?>
<customers>
  <customer cName="John Ben Jan" cID="1" cDomain="History" cCity="Boston"/>
  <customer cName="Lisa Lane" cID="2" cDomain="Chemistry" cCity="LA"/>
  <customer cName="Dagomir Zits" cID="3" cDomain="Heraldry" cCity="Milwaukee"/>
  <customer cName="Sara Careira Santy" cID="4" cDomain="IT" cCity="Miami"/>
</customers>

Each customer element is one record. The example builds a Word template with a region bounded by the merge fields TableStart:customer and TableEnd:customer. The merge fields inside the region are cName and cCity, which match the XML attribute names. You can use the same template for different data sources that provide these fields.

The C++ example uses the XML reader provided with the Aspose.Words C++ SDK and selects the customer records with XPath. The data source starts before the first record. MoveNext advances to the next customer, and GetValue returns the attribute requested by Mail Merge.

ExecuteWithRegions repeats the region for the four customers. The merged document contains the following lines:

John Ben Jan, Boston
Lisa Lane, LA
Dagomir Zits, Milwaukee
Sara Careira Santy, Miami

To merge nested XML records, implement GetChildDataSource to return a data source for the child elements of the current record. If the template has multiple top-level regions, use IMailMergeDataSourceRoot to provide the appropriate data source for each top-level region.

See Also