GroupDocs.Assembly for Python via .NET provides the XmlDataSource class to work with XML data directly in templates. XmlDataSource automatically recognizes data types (numbers, dates, booleans) from XML, making it easier to perform calculations and formatting.
Here are the steps to generate documents from XML:
Create or obtain XML data (from a file, a string, or a stream)
Instantiate XmlDataSource with the XML file’s path, or with a binary stream holding the XML text
Create a template document with expression tags referencing XML elements
Use DocumentAssembler to assemble the template with XmlDataSource
Save the assembled document
Note
XmlDataSource automatically recognizes Int64, Double, Boolean, and DateTime values from XML strings, enabling numeric operations and date formatting in templates without explicit type conversion. The values reach the template as nullable .NET values: a format such as <<[data.Birth]:"dd.MM.yyyy">> works as it is, while a member of the value needs .Value first (<<[data.Birth.Value.Year]>>).
For the XML above, your template can reference elements directly:
Name: <<[data.Name]>>
Age: <<[data.Age]>>
Date of Birth: <<[data.Birth]:"dd.MM.yyyy">>
Email: <<[data.Email]>>
Generate Document from XML String
XmlDataSource reads a file path or a stream, and a str is always taken as a path. To use XML text you already hold in memory, wrap its UTF-8 bytes in io.BytesIO:
The Employees element is one object holding the Employee elements, so the data band iterates company.Employees.Employee. A band over company.Employees visits that single object, and <<[Name]>> then fails with “Can not get the value of member ‘Name’ on type ‘System.Data.DataRow’”.
Configure XML Data Load Options
You can configure how XmlDataSource parses XML. The roster file below has a root element holding only a sequence of Person elements:
By default, if a root XML element contains only a sequence of elements of one type, the engine skips the root object. Set always_generate_root_object to True to always include it. Without it, data above is the sequence itself, and data.Person fails with “Can not get the value of member ‘Person’”.
Advanced Usage Topics
To learn more about working with XML schemas, complex XML structures, XML attributes, and advanced XmlDataSource options, please refer to the advanced usage section.
More resources
GitHub Examples
You may easily run the code above and see the feature in action in our GitHub examples: