利用xml文件来存储多语言的文本资源,在网站运行的时候根据语言来获取相对应的资源。
xml文件示例:
<?xml version="1.0" encoding="utf-8" ?>
<Language>
<Configure>
<LanguageList>
<ch>中文</ch>
<en>English</en>
</LanguageList>
<default>cn</default>
</Configure>
<Global>
<More>
<ch>更多</ch>
<en>more</en>
</More>
</Global>
<Home>
</Home>
</Language>
configure标签中存储配置信息,包括默认语言,全部语言类型等。global标签中存储全局的资源,各控制器标签中存储各控制器的资源,控制器资源优先级高于全局标签。
读取xml类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
namespace EditorOnline.Util
{
public class Language
{
public Dictionary<String, String> ViewBagDic { get; set; }
private const String path = @"\App_GlobalResources\language.xml";
public String truePath { get; set; }
public XmlDocument doc { get; set; }
public String controller { get; set; }
public String language { get; set; }
public Language(String controller, String language, String rootPath)
{
this.ViewBagDic = new Dictionary<string, string>();
this.truePath = rootPath + path;
this.controller = controller;
this.language = language;
LoadXml();
AddLanguage();
}
private void LoadXml()
{
doc = new XmlDocument();
doc.Load(this.truePath);
}
private void AddLanguage()
{
XmlElement root = doc.DocumentElement;
//获取全局语言
XmlNodeList nodeList = root.SelectNodes("/Language/Global");
AddDictionary(nodeList);
XmlNodeList nodeList1 = root.SelectNodes("/Language/" + controller);
AddDictionary(nodeList1);
}
/// <summary>
///
/// </summary>
/// <param name="nodeList"></param>
private void AddDictionary(XmlNodeList nodeList)
{
//遍历全局或者控制器节点
foreach (XmlNode node in nodeList)
{
//遍历tag节点
foreach (XmlNode node1 in node.ChildNodes)
{
//遍历语言节点
foreach(XmlNode node2 in node1.ChildNodes)
{
if (node2.Name == this.language)
{
this.ViewBagDic.Add(node1.Name, node2.InnerText);
}
}
}
}
}
}
}
调用示例:
控制器:
ViewBag.MultLanguage = lg.ViewBagDic;
视图:
@ViewBag.MultLanguage["More"]