public static void Run()
{
#if !NET20
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
// Load the XML document.
XElement orderXml = XElement.Load(dataDir + "PurchaseOrder.xml");
// Query the purchase order xml file using LINQ to extract the order items
// Into an object of an anonymous type.
//
// Make sure you give the properties of the anonymous type the same names as
// The MERGEFIELD fields in the document.
//
// To pass the actual values stored in the XML element or attribute to Aspose.Words,
// we need to cast them to string. This is to prevent the XML tags being inserted into the final document when
// The XElement or XAttribute objects are passed to Aspose.Words.
// ExStart:LINQtoXMLMailMergeorderItems
var orderItems =
from order in orderXml.Descendants("Item")
select new
{
PartNumber = (string)order.Attribute("PartNumber"),
ProductName = (string)order.Element("ProductName"),
Quantity = (string)order.Element("Quantity"),
USPrice = (string)order.Element("USPrice"),
Comment = (string)order.Element("Comment"),
ShipDate = (string)order.Element("ShipDate")
};
// ExEnd:LINQtoXMLMailMergeorderItems
// ExStart:LINQToXMLQueryForDeliveryAddress
var deliveryAddress =
from delivery in orderXml.Elements("Address")
where ((string)delivery.Attribute("Type") == "Shipping")
select new
{
Name = (string)delivery.Element("Name"),
Country = (string)delivery.Element("Country"),
Zip = (string)delivery.Element("Zip"),
State = (string)delivery.Element("State"),
City = (string)delivery.Element("City"),
Street = (string)delivery.Element("Street")
};
// ExEnd:LINQToXMLQueryForDeliveryAddress
// Create custom Aspose.Words mail merge data sources based on the LINQ queries.
MyMailMergeDataSource orderItemsDataSource = new MyMailMergeDataSource(orderItems, "Items");
MyMailMergeDataSource deliveryDataSource = new MyMailMergeDataSource(deliveryAddress);
// ExStart:LINQToXMLMailMerge
string fileName = "TestFile.LINQ.doc";
// Open the template document.
Document doc = new Document(dataDir + fileName);
// Fill the document with data from our data sources.
// Using mail merge regions for populating the order items table is required
// Because it allows the region to be repeated in the document for each order item.
doc.MailMerge.ExecuteWithRegions(orderItemsDataSource);
// The standard mail merge without regions is used for the delivery address.
doc.MailMerge.Execute(deliveryDataSource);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the output document.
doc.Save(dataDir);
// ExEnd:LINQToXMLMailMerge
Console.WriteLine("\nMail merge performed successfully.\nFile saved at " + dataDir);
#else
throw new InvalidOperationException("This example requires the .NET Framework v3.5 or above to run." +
" Make sure that the target framework of this project is set to 3.5 or above.");
#endif
}