Export localized resources from XML to RESX
By Ziya Mollamahmut
The ability to export resources provides flexibility in switching between different resource types, and ease of work on localization by exporting resources to any custom format using custom exporters. The built-in exporters supports exporting from XML to RESX, but you can implement your own exporter to any format.
How to use the built-in XML-to-RESX exporter
Simply inject IXResourceExporter
and call the export method. Below is a razor page sample;
public class ExportModel : PageModel
{
private readonly IXResourceExporter _exporter ;
private readonly ILogger _logger ;
public ExportModel ( IXResourceExporter exporter , ILogger < ExportModel > logger )
{
_exporter = exporter ;
_logger = logger ;
}
public void OnGet ( ) { }
public async Task < IActionResult > OnPostAsync ( string culture , bool approvedOnly , bool overwrite )
{
var totalExported = await _exporter . ExportToResxAsync < LocSource > ( culture , approvedOnly , overwrite ) ;
_logger . LogInformation ( $ "Total { totalExported } resources exported.") ;
return Page ( ) ;
}
}
How to create custom resource exporter
Create a new class that implements IXResourceExporter
and register it in startup.
public class CustomResourceExporter : IXResourceExporter
{
public CustomResourceExporter ( )
{
// ...
}
public async Task < int > ExportToResxAsync < TResource > ( string culture , bool approvedOnly , bool overwriteExistingKeys )
where TResource : class
{
// ...
}
public async Task < int > ExportToResxAsync ( Type type , string culture , bool approvedOnly , bool overwriteExistingKeys )
{
// ...
}
}
Register in startup:
services . AddTransient < IXResourceExporter , CustomResourceExporter > ( ) ;
See the built-in xml resource exporter source code: XmlResourceExporter
Export method parameters
TResource / type: Type of resource file
culture: The culture to export its resources
approvedOnly: Export only resources with approved translations. Auto translated xml resources has the attribute isActive set to false by default.
overwriteExistingKeys: Over write existing resources if any...