asp.net多语言xml解决方案

利用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"]



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值