Avalonia uses XML files to internationalize

Avalonia uses XML files to internationalize

This article explores in depth Avalonia's methods and advantages of using XML files to achieve internationalization. By comparing it with Resx resource files, developers are provided with a basis for choice. Internationalization of XML is suitable for scenarios where user-side modification needs, AI editing is expected, and clear language structure management is pursued. The article details the entire process from creating language files, strong typing generation to specific use and language management, and provides links to relevant resources, such as XML language management packs, case demos and language management tools, Resx resource management extensions, etc., which helps developers quickly get started and apply this internationalization solution in actual projects, improving the global adaptability and user experience of Avalonia applications.

最后更新 12/23/2024 12:34 PM
沙漠尽头的狼
预计阅读 21 分钟
分类
Avalonia UI
标签
.NET C# Avalonia UI internationalization localization

在软件开发日益全球化的今天,Avalonia 的国际化实现策略成为了众多开发者关注的焦点。继上一篇 Avalonia 国际化之路:Resx 资源文件的深度应用与探索 之后,本文将引领大家深入探究如何运用自定义 XML 文件来达成 Avalonia 国际化的目标,开启一段全新的技术探索之旅。

1. Analysis of the advantages of XML in realizing Avalonia UI internationalization

1.1. Break through maintenance limitations and embrace user customization

Resx resource files often limit maintenance permissions to the development side, while custom XML language files stand out for their unique flexibility. It can be output together with executable programs, a feature that opens up a broad space for language file modifications on the user side. Users can not only adjust existing language content according to their own needs, but also easily expand more language types, greatly improving the international adaptability of the software and truly realizing the transformation from development-led to user participation.

1.2. Namespace is added, the structure is clear and orderly

Custom XML files use namespaces to organize language content. This design concept forms an accurate correspondence with the structure of classes. In this way, the architecture of the entire translation document becomes clear and easy to manage and maintain. Whether it is collaborative development in large projects or in the later process of code maintenance and upgrade, work efficiency can be significantly improved and errors and troubles that may be caused by structural confusion can be reduced.

1.3. AI translation is convenient and helps language conversion

In today's era of vigorous development of artificial intelligence, XML files have shown unique advantages in AI translation. With the help of specific tools or platforms, we can easily use AI technology to process XML translation files. For example, by providing simple prompt words, translation results in multiple language versions can be quickly obtained, providing strong support for cross-language communication and software globalization promotion.

The following figure shows the output XML language file:

2. Creation and architecture design of XML files

2.1. Carefully plan language folders

First, we need to create a folder dedicated to storing language files, for example, named "i18n". During this process, special attention should be paid to the fact that the XML file names of different modules under the same output path must remain unique. Because when the program compiles and outputs, if there is an XML file with the same name, it will lead to file replacement and thus cause the loss of language information, which will undoubtedly bring serious obstacles to the internationalization process.

The file prefix can be named with the project name (for easy differentiation), and the suffix is the language and culture name

The following is an example of the project structure after creating the language folder:

The list of compiled output files 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. Strictly build XML file content

以下是上面一个 XML 文件内容(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 specifications and levels. A three-tiered structure is recommended to organize information:

2.2.1. Level 1: Localization node

This node contains three important sub-attributes:

      • language **: A name used to explicitly specify the language. For example,"Chinese (Simplified)" means simplified Chinese.
      • description **: A brief description of the language, such as "simplified Chinese", so that developers and users can quickly understand the basic characteristics of the language.
      • cultureName **: The cultural name of the language, which is a very key symbol in internationalization processing. For example,"zh-CN" represents the cultural area of simplified Chinese. If you are not clear about the cultural name, you can obtain accurate information through Baidu search and other methods.

The following is an example of a basic XML file framework:

<?xml version="1.0" encoding="utf-8"?>

<Localization language="Chinese (Simplified)" description="中文简体" cultureName="zh-CN">
  <!-- 此处将填充具体的模块和语言键值对 -->
</Localization>

2.2.2. Level 2: Function name or class name node

This layer names nodes with function names or class names, and its purpose is to effectively classify the translated files. For example, in a project that contains AI modules, conversion modules, etc., nodes such as "AIModule" and "ConverterModule" can be created respectively, and translation content related to each module can be placed under the corresponding nodes, making the structure of the entire file clearer and easier to manage and find.

The following is an example of an XML file that contains multiple module nodes:

<?xml version="1.0" encoding="utf-8"?>

<Localization language="Chinese (Simplified)" description="中文简体" cultureName="zh-CN">
  <AIModule>
    <!-- AI 模块相关的翻译内容 -->
  </AIModule>
  <ConverterModule>
    <!-- 转换模块相关的翻译内容 -->
  </ConverterModule>
</Localization>

2.2.3. Level 3: Language Key Node

The last layer is the language key node, which directly stores the specific translated text content. For 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 practical applications, although a three-tier structure is recommended, there is no strict limit on the number of nested layers of XML nodes, and developers can flexibly adjust it according to the actual needs and complexity of the project. 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. Strong Typing Strategy for Language Files

In order to make it easier and efficient to use XML translation files in code, we use T4 files to convert XML into strong typing of C#. Specific operations are as follows:

Create a T4 file in the "i18n" directory, for example, name it "Linguage.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 to the XML file, you only need to open the T4 file and perform a save operation, and the corresponding C#class will be automatically generated or updated. 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 provide great convenience for us in subsequent code writing, allowing us to obtain and use the translated text more accurately and conveniently.

4. Specific application practice of XML files in Avalonia

4.1. Install the necessary NuGet package

Install-Package AvaloniaXmlTranslator

This step will introduce necessary functional components into our project and lay the foundation for subsequent internationalization operations.

4.2. Dynamic access to language list

In Avalonia applications, dynamically obtaining the list of languages configured by the program is one of the key steps in switching international interfaces. We can easily get a list of languages with the following code:

List<LocalizationLanguage> languages = I18nManager.Instance.Resources.Select(kvp => kvp.Value).ToList();

Among them, the "LocalizationLanguage" class is defined 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 choose in the drop-down menu, or performing data binding in other interface elements that need to display language information.

4.3. Dynamically switch languages

When users select different languages in the interface, we need to dynamically switch languages in the code. The following is a code example to implement language switching:

var culture = new CultureInfo(language);
I18nManager.Instance.Culture = culture;

The "language" parameter here is the value of the "CultureName" attribute of the "LocalizationLanguage" class. By setting the cultural information of the current thread, we can realize instant switching of interface languages and provide users with a seamless international experience.

4.4. Use translation strings in code

In the code, we can easily obtain the translation string of the current language and culture based on the strongly typed Key. For example:

var title = I18nManager.GetString(Localization.AskBotView.Title); // 获取当前语言
var titleZhCN = I18nManager.Instance.GetResource(Localization.Main.MainView.Title, "zh-CN");	// 获取中文简体
var titleEnUS = I18nManager.Instance.GetResource(Localization.Main.MainView.Title, "en-US");	// 获取英文

In this way, we can flexibly use translated text anywhere in the code, ensuring that what is displayed on the interface matches the language chosen by the user.

The following is the binding use in the 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. Applications in the Axaml interface

Using XML translation files in the Axaml interface is also very convenient. First, you need to introduce the corresponding namespace:

xmlns:language="clr-namespace:Localization"
xmlns:markup="https://codewf.com"

Among them,"markup" is the previously installed auxiliary library namespace, which provides the "I18n" tag extension help class, which is used to bind translated text in the interface;"language" is the C#strongly typed language Key association class namespace generated by T4 files, through which you can associate it with the language key of an XML language file.

The following 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 "ChoiceLanguages View. Language Key" through the "I18n" tag extension. In this way, when the interface language changes, the displayed text of the button will automatically update to the translation content in the corresponding language.

Of course, specifying languages 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}" />

In addition, the Axaml interface also supports binding of dynamic keys, such as:

<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, and dynamically translated text is displayed through the "I18n" tag extension.

5. In-depth analysis of language management functions

为了更好地管理 XML 语言文件,站长开发了部分管理功能,包括多模块 XML 文件合并与 XML 文件编辑,可点击下载 管理工具或自行编译 工具源码,工具程序结构如下:

5.1. Multi-module XML file merge

After running the toolbox, select the "XML Multi-Module File Merge" node under "XML Internationalization Management". By default, the toolbox's own "I18n" directory will open (click "A" to select a different language directory). On the left side of the interface, a list of XML files will be displayed, and you can click on the file to browse its details.

Enter the merged XML file prefix at "B", the default value is "Localization". Then, click the "C" button to perform the file merge operation. The following is an example of the merged effect:

When merging multi-module XML files, you need to pay special attention to the following points:

  1. Be sure to backup your data before merging to prevent data loss or damage due to incorrect merge operations.
  2. It is recommended to ensure that each XML root node is the same before merging, such as naming it "Localization", to ensure that the merged file structure is more standardized and unified.
  3. Duplicate XML nodes of different modules should be avoided, otherwise data conflicts or overrides may occur during the merge process.

The principle of multi-module XML file merging is actually very simple, that is, XML files under the same language suffix are merged into a root node, thereby realizing the integration and centralized management of language data.

5.2. XML file editing

At present, the XML file editing function is relatively basic and only supports modifications to existing languages.

In subsequent development plans, the webmaster will further improve the XML file editing function and is expected to support the following operations:

  1. Modifiable Key: Allows users to modify existing language keys to adapt to changes in project requirements or correct wrong key naming.
  2. Keys can be added and deleted: Provides flexible key management functions, allowing users to add new language keys or delete keys that are no longer in use according to actual needs, making the content of XML files more accurate and efficient.
  3. Languages can be added and deleted: In addition to the management of keys, it will also support the addition of new language types and the removal of languages that are no longer needed, further expanding the scope of international support for XML documents.
  4. One-click translation: With the help of advanced AI translation technology, the content in XML files can be translated into multiple languages with one click, which greatly improves translation efficiency and reduces the workload and cost of manual translation.

5.3. Smart application of AI translation

During the translation process of XML documents, we can cleverly use AI translation technology to improve efficiency. For example, by writing the following prompt words:

帮我将以下的中文简体 XML 翻译文件再翻译成中文繁体、英文、日语 3 个版本,不用回复其他文字,谢谢:

```xml
<?xml version="1.0" encoding="utf-8"?>

<Localization language="Chinese (Simplified)" description="中文简体" cultureName="zh-CN">
	<MainModule>
		<Title>Code workshop toolbox</Title>
		<SearchToolTip>Search what you think</SearchToolTip>
		<WeChat>Contact WeChat: codewf</WeChat>
		<WeChatPublic>Pay attention to Weixin Official Accounts: Dotnet9</WeChatPublic>
		<DesiredAvailabilityNotification>Everything you want, please let me know if you don't have it. </DesiredAvailabilityNotification>
		<AccessToolbox>Access the online toolbox</AccessToolbox>
	<AboutView>
		<Title>About</Title>
		<Description>This project is only for learning</Description>
	</AboutView>
</Localization>
```

By providing the above XML content to AI, you can obtain the corresponding translation versions of traditional Chinese, English, and Japanese, providing a fast and convenient translation path for internationalization work, with remarkable results, as shown in the following example figure:

6. summary and outlook

In Avalonia's journey of internationalization, Resx resource files and custom XML files are two important implementation methods, and developers should make reasonable choices based on specific needs.

6.1. Applicable scenarios for Resx resource files

  1. When the project has no user-side modification requirements, Resx resource files can be efficiently operated through tools such as Resx Manager due to their convenient management in the development environment.
  2. For projects that focus on the efficiency of resource file management during the development process and do not require users to participate in language content adjustment, Resx resource files can well meet the needs and ensure the smooth advancement of the project's internationalization process.

6.2. Advantages of customizing XML files

  1. If the project has user-side modification requirements, the custom XML file can shine. It allows users to flexibly adjust the language content of the software according to their own usage scenarios and language habits, greatly improving the user experience and software adaptability.
  2. When AI editing is needed for language processing, the format of XML files is easier to interact with AI tools, making full use of the advantages of AI technology to achieve efficient translation and language management.
  3. For projects that pursue clear and orderly language structure management to facilitate team collaboration, code maintenance, and project expansion, the namespace organization of customized XML files and flexible node structure can provide strong support.

This article describes in detail the entire process of Avalonia's internationalization using custom XML files, including XML file creation, strong type generation, specific application in Avalonia, and language management functions. At the same time, developers are provided with rich code examples, detailed operating steps and relevant picture descriptions, aiming to help developers quickly get started and use this international solution skillfully. The relevant resources involved in this article are as follows:

Looking to the future, with the continuous development of technology and the increasing variety of application scenarios, the realization method of Avalonia internationalization will continue to evolve and improve. We look forward to seeing the emergence of more convenient and efficient tools and technologies, further simplifying the international development process, improving the global quality of software, and bringing users a more excellent cross-language experience. Whether it is Resx resource files or custom XML files, they will continue to play an important role in their respective fields of application and jointly promote the continuous advancement of Avalonia's internationalization process.

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 8/9/2025

Lang.Avalonia: Avalonia's multi-language solution seamlessly supports three formats: Resx/XML/JSON

This is a multi-language management library specially designed for the Avalonia framework. It reconstructs the multi-language support logic through plug-in architecture. It is not only compatible with traditional Resx resource files, but also adds support for XML and JSON formats. It also provides type-safe resource references, dynamic language switching and other capabilities make multi-language development simpler and more efficient.

继续阅读