As software development becomes increasingly globalized today, the internationalization strategy of Avalonia has become a focal point for many developers. Following the previous article Avalonia Internationalization Road: Deep Application and Exploration of Resx Resource Files, this article will guide you to delve into how to use custom XML files to achieve Avalonia internationalization, embarking on a new technical exploration journey.
1. Analyzing the Advantages of Implementing Avalonia UI Internationalization with XML
1.1. Breaking Through Maintenance Limitations, Embracing User Customization
Resx resource files often restrict maintenance permissions to the development side. In contrast, custom XML language files stand out with their unique flexibility. They can be output along with the executable program. This feature opens up a broad space for users to modify language files. Users can not only adjust existing language content according to their needs but also easily extend to more languages, greatly enhancing the software's adaptability in internationalization, truly realizing a shift from development-led to user-participated transformation.
1.2. Namespace Support for Clear and Ordered Structure
Custom XML files organize language content using namespaces. This design concept precisely corresponds to the structure of classes. In this way, the entire translation file architecture becomes clear and easy to manage and maintain. Whether in team collaboration during large projects or in later code maintenance and upgrades, work efficiency is significantly improved, and errors and troubles caused by structural confusion are reduced.
1.3. AI Translation Convenience, Aiding Language Conversion
In the current era of booming artificial intelligence, XML files demonstrate unique advantages in AI translation. Using specific tools or platforms, we can conveniently process XML translation files with AI technology. For example, by providing simple prompts, we can quickly obtain translation results in multiple languages, offering strong support for cross-language communication and global software promotion.
The image below shows the output XML language files:

2. Creating XML Files and Designing Architecture
2.1. Carefully Planning Language Folders
First, we need to create a dedicated folder for storing language files, for example, named "i18n". During this process, special attention must be paid: XML filenames of different modules under the same output path must be unique. Because when the program compiles and outputs, if there are XML files with the same name, file replacement will occur, causing language information loss, which will inevitably bring serious obstacles to the internationalization process.
The file prefix can be named after the project (for easy distinction), and the suffix is the language culture name.
The following is an example of the project structure after creating the language folder:

The file list after compilation and output is as follows:
AIModule.en-US.xml
AIModule.ja-JP.xml
AIModule.zh-CN.xml
AIModule.zh-Hant.xml
ConverterModule.en-US.xml
ConverterModule.ja-JP.xml
ConverterModule.zh-CN.xml
ConverterModule.zh-Hant.xml
DevelopmentModule.en-US.xml
DevelopmentModule.ja-JP.xml
DevelopmentModule.zh-CN.xml
DevelopmentModule.zh-Hant.xml
MainModule.en-US.xml
MainModule.ja-JP.xml
MainModule.zh-CN.xml
MainModule.zh-Hant.xml
XmlTranslatorManagerModule.en-US.xml
XmlTranslatorManagerModule.ja-JP.xml
XmlTranslatorManagerModule.zh-CN.xml
XmlTranslatorManagerModule.zh-Hant.xml
2.2. Rigorously Building XML File Content
Below is the content of one XML file (AIModule.zh-CN.xml):
<?xml version="1.0" encoding="utf-8"?>
<Localization language="Chinese (Simplified)" description="中文简体" cultureName="zh-CN">
<AIModule>
<Title>AI</Title>
</AIModule>
<AskBotView>
<Title>智能问答助手</Title>
<Description>一键提问,即刻获取答案,智能问答助手为您解惑。</Description>
</AskBotView>
<PolyTranslateView>
<Title>AI一键多语种翻译神器</Title>
<Description>轻松实现一键翻译,支持多种语言互译,让沟通无界限!</Description>
</PolyTranslateView>
<Title2SlugView>
<Title>AI一键转URL Slug</Title>
<Description>轻松将中文、英文等文章标题一键转换成英文URL Slug。</Description>
</Title2SlugView>
<ChoiceLanguagesView>
<LanguageKey>语言</LanguageKey>
<Selectable>可选择的</Selectable>
<Selected>已选择</Selected>
</ChoiceLanguagesView>
</Localization>
The content structure of XML files follows certain standards and hierarchy. A three-layer structure is recommended for organizing information:
2.2.1. The First Layer: Localization Node
This node contains three important attributes:
- language: Used to explicitly specify the language name, e.g., "Chinese (Simplified)" for Simplified Chinese.
- description: A brief description of the language, e.g., "中文简体", so developers and users can quickly understand the basic characteristics of the language.
- cultureName: The culture name of the language, a very critical identifier in internationalization processing, e.g., "zh-CN" for the Simplified Chinese culture region. If you are not sure about the culture name, you can obtain accurate information via Baidu search.
Below is a basic XML file framework example:
<?xml version="1.0" encoding="utf-8"?>
<Localization language="Chinese (Simplified)" description="中文简体" cultureName="zh-CN">
<!-- Specific module and language key-value pairs will be filled here -->
</Localization>
2.2.2. The Second Layer: Function Name or Class Name Node
This layer uses function name or class name to name nodes. Its purpose is to effectively categorize translations by function. For example, in a project containing an AI module, a converter module, etc., you can create nodes like "AIModule", "ConverterModule", and place the relevant translation content under each corresponding node, making the overall file structure clearer and easier to manage and locate.
Below is an example of an XML file containing multiple module nodes:
<?xml version="1.0" encoding="utf-8"?>
<Localization language="Chinese (Simplified)" description="中文简体" cultureName="zh-CN">
<AIModule>
<!-- Translation content related to AI module -->
</AIModule>
<ConverterModule>
<!-- Translation content related to Converter module -->
</ConverterModule>
</Localization>
2.2.3. The Third Layer: Language Key Node
The last layer consists of language key nodes. These nodes directly store the specific translation text content. Example:
<?xml version="1.0" encoding="utf-8"?>
<Localization language="Chinese (Simplified)" description="中文简体" cultureName="zh-CN">
<AIModule>
<Title>AI</Title>
</AIModule>
<AskBotView>
<Title>智能问答助手</Title>
<Description>一键提问,即刻获取答案,智能问答助手为您解惑。</Description>
</AskBotView>
</Localization>
In actual use, although a three-layer structure is recommended, there is no strict limitation on the nesting depth of XML nodes. Developers can adjust flexibly according to actual project needs and complexity. For example:
<?xml version="1.0" encoding="utf-8"?>
<Localization language="Chinese (Simplified)" description="中文简体" cultureName="zh-CN">
<AIModule>
<Title>AI</Title>
</AIModule>
<AI>
<AskBotView>
<Title>智能问答助手</Title>
<Description>一键提问,即刻获取答案,智能问答助手为您解惑。</Description>
</AskBotView>
</AI>
<Translate>
<Baidu>
<PolyTranslateView>
<Title>AI一键多语种翻译神器</Title>
<Description>轻松实现一键翻译,支持多种语言互译,让沟通无界限!</Description>
</PolyTranslateView>
</Baidu>
<Google>
<PolyTranslateView>
<Title>AI一键多语种翻译神器</Title>
<Description>轻松实现一键翻译,支持多种语言互译,让沟通无界限!</Description>
</PolyTranslateView>
</Google>
</Translate>
</Localization>
3. Strongly Typed Generation Strategy for Language Files
To use XML translation files more conveniently and efficiently in code, we use T4 files to convert XML into C# strongly typed classes. The specific steps are as follows:
Create a T4 file in the "i18n" directory, for example named "Language.tt", and fill in the following code:
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="System.IO" #>
<#@ output extension=".cs" #>
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
<#
string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
string xmlFilePath = Directory.GetFiles(templateDirectory, "*.xml").FirstOrDefault();
if (xmlFilePath!= null)
{
XDocument xdoc = XDocument.Load(xmlFilePath);
var classNodes = xdoc.Nodes().OfType<XElement>().DescendantsAndSelf().Where(e => e.Descendants().Count() == 0).Select(e => e.Parent).Distinct().ToList();
foreach (var classNode in classNodes)
{
var namespaceSegments = classNode.Ancestors().Reverse().Select(node => node.Name.LocalName);
string namespaceName = string.Join(".", namespaceSegments);
GenerateClasses(classNode, namespaceName);
}
}
else
{
Write("XML file not found, please ensure that there is an XML file in the current directory");
}
void GenerateClasses(XElement element, string namespaceName)
{
string className = element.Name.LocalName;
StringBuilder classBuilder = new StringBuilder();
classBuilder.AppendLine($"namespace {namespaceName}");
classBuilder.AppendLine("{");
classBuilder.AppendLine($" public static class {className}");
classBuilder.AppendLine(" {");
var fieldNodes = element.Elements();
foreach (var fieldNode in fieldNodes)
{
var propertyName = fieldNode.Name.LocalName;
var languageKey = $"{namespaceName}.{className}.{propertyName}";
classBuilder.AppendLine($" public static readonly string {propertyName} = \"{languageKey}\";");
}
classBuilder.AppendLine(" }");
classBuilder.AppendLine("}");
Write(classBuilder.ToString());
}
#>
After each modification of the XML file, simply open this T4 file and perform a save operation; the system will automatically generate or update the corresponding C# classes. For example:
//...
namespace Localization
{
public static class AIModule
{
public static readonly string Title = "Localization.AIModule.Title";
}
}
namespace Localization
{
public static class AskBotView
{
public static readonly string Title = "Localization.AskBotView.Title";
public static readonly string Description = "Localization.AskBotView.Description";
}
}
//...
These generated strongly typed classes will greatly facilitate subsequent code writing, allowing us to obtain and use translation texts more accurately and conveniently.
4. Practical Application of XML Files in Avalonia
4.1. Install the Required NuGet Package
Install-Package AvaloniaXmlTranslator
This step introduces the necessary functional components into the project, laying the foundation for subsequent internationalization operations.
4.2. Dynamically Obtain the Language List
In an Avalonia application, dynamically obtaining the language list configured in the program is one of the key steps to achieving internationalization interface switching. With the following code, we can easily get the language list:
List<LocalizationLanguage> languages = I18nManager.Instance.Resources.Select(kvp => kvp.Value).ToList();
The definition of the "LocalizationLanguage" class is as follows:
public class LocalizationLanguage
{
public string Language { get; set; } = (string) null;
public string Description { get; set; } = (string) null;
public string CultureName { get; set; } = (string) null;
//...
}
After obtaining the language list, we can use it for interface binding, such as displaying language options for users to select in a dropdown, or for data binding in other interface elements that need to display language information.
4.3. Dynamically Switch Languages
When the user selects a different language in the interface, we need to implement dynamic language switching in code. Below is a code example for switching languages:
var culture = new CultureInfo(language);
I18nManager.Instance.Culture = culture;
Here, the "language" parameter is the value of the "CultureName" property of the "LocalizationLanguage" class. By setting the culture information of the current thread, we can achieve instant switching of interface language, providing users with a seamless internationalization experience.
4.4. Using Translated Strings in Code
In code, we can conveniently obtain the translation string for the current language culture based on the strongly typed key. For example:
var title = I18nManager.GetString(Localization.AskBotView.Title); // Get current language
var titleZhCN = I18nManager.Instance.GetResource(Localization.Main.MainView.Title, "zh-CN"); // Get Simplified Chinese
var titleEnUS = I18nManager.Instance.GetResource(Localization.Main.MainView.Title, "en-US"); // Get English
In this way, we can flexibly use translated text anywhere in the code, ensuring that the content displayed in the interface matches the language selected by the user.
Below is an example of binding in code:
//...
var header = item is UserControl { DataContext: ITabItemBase tabItem }
? tabItem.TitleKey
: item?.GetType().ToString();
var newTabItem = new TabItem { Content = item };
newTabItem.Bind(TabItem.HeaderProperty, new I18nBinding(header));
regionTarget.Items.Add(newTabItem);
//...
4.5. Application in Axaml Interfaces
Using XML translation files in Axaml interfaces is also very convenient. First, we need to import the corresponding namespaces:
xmlns:language="clr-namespace:Localization"
xmlns:markup="https://codewf.com"
Here, "markup" is the namespace for the auxiliary library installed earlier, which provides the "I18n" markup extension helper class for binding translated text in interfaces; "language" is the namespace for the C# strongly typed language key association classes generated by the T4 file, which can be used to associate with the language keys in the XML language file.
Below is an example of using translated text in a control:
<Button
Grid.Row="3"
Grid.Column="1"
Margin="10,0,0,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Command="{Binding RaiseChoiceLanguagesCommand}"
Content="{markup:I18n {x:Static language:ChoiceLanguagesView.LanguageKey}}" />
In the above example, the "Content" property of the "Button" control is bound to the translated text corresponding to "ChoiceLanguagesView.LanguageKey" via the "I18n" markup extension. Thus, when the interface language changes, the display text of the button will automatically update to the corresponding language translation.
Specifying a language is also supported:
<SelectableTextBlock u:FormItem.Label="Current Thread" Text="{markup:I18n {x:Static developModuleLanguage:Title2SlugView.Title}}" />
<SelectableTextBlock u:FormItem.Label="en-US" Text="{markup:I18n {x:Static developModuleLanguage:Title2SlugView.Title}, CultureName=en-US}" />
<SelectableTextBlock u:FormItem.Label="ja-JP" Text="{markup:I18n {x:Static developModuleLanguage:Title2SlugView.Title}, CultureName=ja-JP}" />
<SelectableTextBlock u:FormItem.Label="zh-CN" Text="{markup:I18n {x:Static developModuleLanguage:Title2SlugView.Title}, CultureName=zh-CN}" />
<SelectableTextBlock u:FormItem.Label="zh-Hant" Text="{markup:I18n {x:Static developModuleLanguage:Title2SlugView.Title}, CultureName=zh-Hant}" />
Additionally, Axaml interfaces support dynamic key binding, for example:
<u:Banner
Classes.Bordered="{Binding Bordered}"
Content="{markup:I18n {Binding SelectedMenuItem.Description}}"
Header="{markup:I18n {Binding SelectedMenuItem.Name}}"
Type="{Binding SelectedType}" />
In this example, the "Content" and "Header" properties of the "Banner" control are bound to the dynamic "SelectedMenuItem.Description" and "SelectedMenuItem.Name" properties respectively, achieving dynamic translation text display through the "I18n" markup extension.
5. In-Depth Analysis of Language Management Functions
To better manage XML language files, the site owner developed some management features, including multi-module XML file merging and XML file editing. You can click to download the management tool or compile the tool source code yourself. The tool program structure is as follows:

5.1. Multi-Module XML File Merging
After running the toolbox, select the "XML Internationalization Management" node and then "XML Multi-Module File Merge". By default, the tool will open its own "I18n" directory (click "A" to select another language directory). On the left side of the interface, the XML file list will be displayed; click a file to browse its detailed content.

At "B", enter the prefix for the merged XML file; the default value is "Localization". Then click the "C" button to execute the file merge operation. Below is an example of the effect after merging:

When performing multi-module XML file merging, special attention should be paid to the following points:
- Be sure to back up data before merging to prevent data loss or corruption due to merge operation errors.
- It is recommended to ensure that the root node of each XML is the same before merging, for example, all named "Localization". This ensures a more standardized and unified structure after merging.
- XML nodes from different modules should avoid duplication; otherwise, data conflicts or overwriting issues may occur during the merge process.
The principle of multi-module XML file merging is actually very simple: merge XML files with the same language suffix under one root node, thereby integrating and centrally managing language data.
5.2. XML File Editing
Currently, the XML file editing function is relatively basic; it only supports modifying existing languages.

In future development plans, the site owner will further improve the XML file editing function, which is expected to support the following operations:
- Key Modification: Allow users to modify existing language keys to adapt to project requirement changes or correct incorrect key naming.
- Key Addition and Deletion: Provide flexible key management functions, allowing users to add new language keys or delete obsolete keys as needed, making the XML file content more precise and efficient.
- Language Addition and Deletion: In addition to key management, support adding new language types and deleting languages that are no longer needed, further expanding the internationalization support scope of XML files.
- One-Click Translation: Leverage advanced AI translation technology to achieve one-click translation of XML file content into multiple languages, greatly improving translation efficiency and reducing manual translation workload and cost.
5.3. Clever Application of AI Translation
In the process of translating XML files, we can cleverly use AI translation technology to improve efficiency. For example, by writing the following prompt:
Help me translate the following Simplified Chinese XML translation file into three versions: Traditional Chinese, English, and Japanese. No need to reply with other text, thank you:
```xml
<?xml version="1.0" encoding="utf-8"?>
<Localization language="Chinese (Simplified)" description="中文简体" cultureName="zh-CN">
<MainModule>
<Title>码坊工具箱</Title>
<SearchToolTip>搜你所想</SearchToolTip>
<WeChat>联系微信号:codewf</WeChat>
<WeChatPublic>关注微信公众号:Dotnet9</WeChatPublic>
<DesiredAvailabilityNotification>想要的都有,没有请告知。</DesiredAvailabilityNotification>
<AccessToolbox>访问在线工具箱</AccessToolbox>
<AboutView>
<Title>关于</Title>
<Description>本项目只用于学习使用</Description>
</AboutView>
</Localization>
```
Provide the above XML content to AI, and you can obtain the corresponding Traditional Chinese, English, and Japanese translation versions. This provides a fast and convenient translation approach for internationalization work, with remarkable effects, as shown in the example image below:

6. Summary and Outlook
In the journey of Avalonia internationalization, Resx resource files and custom XML files are two important implementation methods. Developers should make reasonable choices based on specific needs.
6.1. Applicable Scenarios for Resx Resource Files
- When the project has no user-side modification requirements, Resx resource files are an ideal choice due to their convenient management in the development environment, which can be efficiently operated via tools like Resx Manager.
- For projects that focus on the efficiency of resource file management during development and do not require user involvement in language content adjustments, Resx resource files can well meet the needs, ensuring the smooth progress of the project's internationalization.
6.2. Strengths of Custom XML Files
- If the project has user-side modification requirements, custom XML files can shine. They allow users to flexibly adjust the language content of the software according to their own usage scenarios and language habits, greatly enhancing user experience and software adaptability.
- In scenarios that require AI-assisted editing for language processing, the XML file format is easier to interact with AI tools, fully leveraging the advantages of AI technology to achieve efficient translation and language management.
- For projects that pursue clear and ordered language structure management to facilitate team collaboration, code maintenance, and project expansion, the namespace organization and flexible node structure of custom XML files provide strong support.
This article elaborates on the entire process of using custom XML files to achieve internationalization in Avalonia, including XML file creation, strongly typed generation, specific application in Avalonia, and language management functions. At the same time, it provides developers with rich code examples, detailed operation steps, and relevant image explanations to help developers quickly get started and skillfully use this internationalization solution. The related resources involved in the article are as follows:
- XML Language Management Package: AvaloniaXmlTranslator
- Case Demo and Language Management Tool: CodeWF.Toolbox
- Resx Resource Management Extension: Resx Manager
Looking ahead, as technology continues to develop and application scenarios become increasingly diverse, the implementation methods of Avalonia internationalization will also evolve and improve. We look forward to seeing more convenient and efficient tools and technologies emerge, further simplifying the internationalization development process, enhancing the global quality of software, and providing users with a superior cross-language experience. Whether Resx resource files or custom XML files, they will continue to play important roles in their respective applicable fields, jointly driving the continuous progress of Avalonia internationalization.