Thursday, May 11, 2006

XML-based translations in .NET

Somebody asked me how we do string translations in web pages, knowing that we work in several languages.

There are probably better systems to effect translations on web pages and ASPX, but we opted for converting our old and trusty XML based functions that we used for years when doing classic ASP at work. It is fast and easy.

All our extranet pages are done in three languages. A user setup gives them the choice of languages so when they login (as said we only work on a password-based extranet for our customers), we know who they are and what their choice is.

Based on this info, every string gets translated from an XML file with the same name as the page in use.

As an example, this excerpt sets the text in labels and buttons:

this.lblInformation.Text=commonfunc.Get_Xml(xmlText, "lblInformation");
this.btnSubmit.Text=commonfunc.Get_Xml(xmlText,"btnsubmit");
this.btnBack.Text=commonfunc.Get_Xml(xmlText,"btnback");


An XML file with the same name as the page contains the strings. The language is kept in a session variable containing "EN"/"SP"/"PO" for English, Spanish and Portuguese, the three languages we deal with on a daily basis.

Example: ./XML/Default.xml would correspond to ./Default.aspx

{?xml version="1.0" encoding="utf-8" ?}
{root}
{EN}
{lblinformation}Click on a user name to validate their current Service Entitlements.{/lblinformation}
{btnsubmit}Submit{/btnsubmit}
{btnback}Back{/btnback}
{/EN}
{SP}
{lblinformation}Seleccione una persona para validar los servicios autorizados{/lblinformation}
{btnsubmit}Enviar{/btnsubmit}
{btnback}Volver{/btnback}
{/SP}
{PO}
{lblinformation}Selecione uma pessoa para validar os serviços autorizados{/lblinformation}
{btnsubmit}Enviar{/btnsubmit}
{btnback}Voltar{/btnback}
{/PO}
{/root}


(note that the angle brackets in XML strings have been changed to braces for HTML parser avoidance)

At the beginning of the page we instantiate the object containing the functionality like so:

XmlDocument xmlText = new XmlDocument();
xmlText = commonfunc.Load_Xml();


The function is very simple:

public string Get_Xml(XmlDocument doc, string inStr)
{
string aNodePrefix = "*/"+HttpContext.Current.Session["UserLanguage"]+"/";
return doc.SelectSingleNode(aNodePrefix +inStr).InnerText;
}


Of course the function could be more generic by passing parameters on what the XML filename is, as opposed to being always the same name as the current page, and the desired language could also be optionally passed but the current system is perfect for our needs.

1 comment:

  1. Anonymous7:38 AM EDT

    Hi Alex,
    Great way for translation. It's simple and useful.
    Congratulations!

    Strength Always!

    ReplyDelete