Translate Resource Files

Tags: Google, API, Translation

Today at work I was faced with the problem of checking if an application properly supported localization. I wrote a quick console application that takes the file location of the resource file that you want to translate and spits out a bunch of resource files in languages supported by Google Translation. Quite simple, but quite practical if you need to check if your UI works in different languages.

This example assumes that your base resource file is English, but you can change that in the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Globalization;
using System.Web;

namespace ResourceFileTranslater
{
	class Program
	{
		static void Main(string[] args)
		{
			if (args.Length == 0) { return; }
			string saveFileFormat = args[0].Replace(".resx", ".{0}.resx");
			XmlDocument resDoc = new XmlDocument();

			foreach (string language in supportedCultures)
			{
				try
				{
					CultureInfo ci = CultureInfo.CreateSpecificCulture(language);
					string saveFile = string.Format(saveFileFormat, ci.Name);
					resDoc.Load(args[0]);
					XmlNodeList dataNodes = resDoc.SelectNodes("//data");
					foreach (XmlNode node in dataNodes)
					{
						foreach (XmlNode childNode in node.ChildNodes)
						{
							if (childNode.NodeType == XmlNodeType.Element)
							{
								if (!string.IsNullOrEmpty(childNode.InnerText))
								{
									childNode.InnerText = Reimers.Google.Translator.TranslateText(childNode.InnerText, CultureInfo.CreateSpecificCulture("en"), ci, "http://www.url.com", "LongGoogleKey");
									childNode.InnerText = HttpUtility.HtmlDecode(childNode.InnerText);
								}
								break;
							}
						}
					}
					resDoc.Save(saveFile);
				}
				finally
				{
					Console.WriteLine(language);
				}
			}

		}

		private static string[] supportedCultures = new string[] { 
            "sq", "ar", "bg", "ca", /*"zh",*/ "hr", "cs", "da", "et", /*"fil",*/ "fi", "fr", 
            "gl", "de", "el", "he", "hi", "hu", "id", "it", "ja", "ko", "lv", "lt", 
            /*"mt",*/ "pl", "pt", "ro", "ru", "sr", "sk", "sl", "es", "sv", "th", "tr", "uk", "vi" };
	}
}

Of course, using an automatic translation tool, should not be used for release code. Make sure you check the translation before you release your application.

Latest Tweets