(实战篇)如何实现多语言
承接上一篇,说完如何缓存之后,这一期我们来关注”多语言的实现“,项目中多语言的实现在基类里实现,
直接过代码,来看实现思路
(1) 基类PageBase 里重载某个事件
public class PageBase : System.Web.UI.Page /// <summary> /// OnPreRenderComplete重载 /// </summary> /// <param name="e"></param> protected override void OnPreRenderComplete(EventArgs e) { LoadLanguageInfo(this, "Common"); }
(2)来看LoadLanguageInfo方法,它的作用主要是递归页面的所有控件,然后赋值
/// <summary> /// 映射多语言信息 /// </summary> /// <param name="control">用户控件</param> /// <param name="resourceType">资源类型</param> public static void LoadLanguageInfo(System.Web.UI.Control control, string resourceType) { if (control.Controls.Count > 0) { for (var i = 0; i < control.Controls.Count; i++) { LoadLanguageInfo(control.Controls[i], resourceType); } } else { ControlOpertion(control); } }
(3)来看ControlOpertion方法,即为实际的控件名称赋值
/// <summary> /// 控件中英文赋值 /// </summary> /// <param name="control"></param> private static void ControlOpertion(System.Web.UI.Control control) { var strLangValue = string.Empty; switch (control.GetType().ToString()) { case "System.Web.UI.WebControls.Label": if (!string.IsNullOrEmpty(control.ID)) { try { strLangValue = FwConfig.GetString(FwConfig.ObjectToNullStr(control.ID)); } catch { } finally { if (!string.IsNullOrEmpty(strLangValue)) ((Label) (control)).Text = strLangValue; } } break; case "System.Web.UI.WebControls.Button": if (!string.IsNullOrEmpty(control.ID)) { try { strLangValue = FwConfig.GetString(FwConfig.ObjectToNullStr(control.ID)); } catch { } finally { if (!string.IsNullOrEmpty(strLangValue)) ((Button)(control)).Text = strLangValue; } } break; //多个case,遍历其它类型的控件 } }
(4)GetString获取当前控件的中英文名称
/// <summary> /// 根据资源 ID 返回相应的资源 /// </summary> /// <example> /// <code> /// string strMessage=RMUtility.GetString("password"); /// //如果用户选择中文版 strMessage=“密码”,英文版strMessage="Password" /// </code> /// </example> /// <param name="ResourceID">资源 ID</param> /// <returns>根据当前的语言环境,返回相应的文本</returns> public static string GetString(string ResourceID) { if (string.IsNullOrEmpty(ResourceID)) { return ""; } Hashtable messages = GetResource(); //转换成大写,不出分大小写 ResourceID = ResourceID.ToUpper(); if (messages.ContainsKey(ResourceID)) { return (string)messages[ResourceID]; } return ""; }
(5)GetResource函数里查找xml文件,将中英文信息放进hashtable,然后缓存,
读取时直接读取缓存,有则直接返回,没有则先放进缓存,然后返回
/// <summary> /// 根据当前的语言环境获取资源字典 /// </summary> /// <returns>key : 资源 ID ,value : 对应的资源</returns> private static Hashtable GetResource() { string currentCulture = CurrentCultureName; string defaultCulture = DefaultCulture; string cacheKey = currentCulture; if (string.IsNullOrEmpty(cacheKey)) return new Hashtable(); //////如果字典在缓冲中不存在,则重新加载 if (HttpRuntime.Cache[cacheKey] == null) { Hashtable resource = new Hashtable(); if (defaultCulture != currentCulture) { try { LoadResource(resource, currentCulture, cacheKey); } catch (FileNotFoundException) { } } else { LoadResource(resource, defaultCulture, cacheKey); } } return (Hashtable)HttpRuntime.Cache[cacheKey]; }
(6)LoadResource函数将读取的xml信息放进缓存
/// <summary> /// 从 XML 中加载资源 /// </summary> /// <param name="resource">资源字典</param> /// <param name="culture"></param> /// <param name="cacheKey"></param> private static void LoadResource(Hashtable resource, string culture, string cacheKey) { string file = FwConfig.CurContext.Server.MapPath(CurContext.Request.ApplicationPath + "Languages") + '\\' + culture + "\\Resource.xml"; XmlDocument xml = new XmlDocument(); xml.Load(file); XmlNode selectSingleNode = xml.SelectSingleNode("Resources"); if (selectSingleNode != null) { XmlNodeList nodeList = selectSingleNode.ChildNodes; foreach (XmlNode xn in nodeList) //遍历所有子节点 { XmlElement xe = (XmlElement)xn; //将子节点类型转换为XmlElement类型 string strID = ObjectToNullStr(xe.GetAttribute("ID")); XmlNodeList nls = xe.ChildNodes; //继续获取xe子节点的所有子节点 foreach (XmlNode xn1 in nls) //遍历 { if (xn1.NodeType != XmlNodeType.Comment) { if (xn1.Attributes != null) resource[ObjectToNullStr(xn1.Attributes["name"].Value).ToUpper()] = ObjectToNullStr(xn1.InnerText); //转换成大写 //resource[(strID + ObjectToNullStr(xn1.Attributes["name"].Value)).ToUpper()] = ObjectToNullStr(xn1.InnerText); //转换成大写 } } } } //把加载的资源存在缓冲中 HttpRuntime.Cache.Insert(cacheKey, resource, new CacheDependency(file), DateTime.MaxValue, TimeSpan.Zero); }
至此,完整的多语言实现思路和代码如上所述,以供以后项目参考和学习之用!
备注:xml文件的格式如下:
<Resources> <Resource ID ="Common"> <item name="lblName">中文信息</item> <item name="lblAddress">中广核集团信息技术中心</item> <item name="btnGo">转到首页</item> </Resource> </Resources> 中文xml文件 <Resources> <Resource ID ="Common"> <item name="lblName">english message</item> <item name="lblAddress">cna</item> <item name="btnGo">go to default page</item> </Resource> </Resources> 英文xml文件