• C#动态生成XML并在前台用javascript读取


    考虑到网站首页使用动态页面的话会影响服务器性能,所以采用javascript来实现首页的动态更新。

    原理,以发新闻稿为例,当后台发出一条新闻后,通过访问数据库动态生成一个XML文件,保存新闻的信息,当打开前台页面时,使用javascript读取XML文件并显示。

    后台代码:

    sseEntities _db = new sseEntities();
                var newsToView = (from n in _db.News select n).ToArray().Reverse().ToList();

                XmlDocument xd = new XmlDocument();
                XmlDeclaration xde;
                xde = xd.CreateXmlDeclaration("1.0", "GBK", null);
                xd.AppendChild(xde);

                XmlElement newslist = xd.CreateElement("newslist");
                xd.AppendChild(newslist);
                XmlNode root = xd.SelectSingleNode("newslist");
                XmlElement [] news = new XmlElement [4];
                XmlElement [] text = new XmlElement [4];
                XmlElement [] img = new XmlElement[4];
                for (int i = 0; i < 4; i++)
                {
                    news[i] = xd.CreateElement("news");
                    text[i] = xd.CreateElement("text");
                    img[i] = xd.CreateElement("img");
                    news[i].SetAttribute("id", i.ToString());
                    if (i < newsToView.Count)
                    {
                        text[i].InnerText = newsToView[i].Title;
                        img[i].InnerText = "Content/newsimages/slider_item1.png";
                    }
                    else
                    {
                        text[i].InnerText = "";
                        img[i].InnerText = "";
                    }
                    news[i].AppendChild(text[i]);
                    news[i].AppendChild(img[i]);
                    root.AppendChild(news[i]);
                }
                xd.Save(Server.MapPath("../Sources/News.xml"));

    前台读取代码:

    <script type="text/javascript">
            function loadXML(xmlFile) {
                var xmlDoc;集装箱运费
                if (!window.ActiveXObject) {
                    var parser = new DOMParser();
                    xmlDoc = parser.parseFromString(xmlFile, "text/xml");
                } else {
                    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                    xmlDoc.async = "false";
                    xmlDoc.load(xmlFile);
                }
                return xmlDoc;iphone5
            }
            var xmlDoc = loadXML("Sources/News.xml");
            //解析xml文件,判断是否出错
            if (xmlDoc.parseError.errorCode != 0) {
                alert(xmlDoc.parseError.reason);
            }
            //获得根节点
            var nodes = xmlDoc.documentElement.childNodes;
        </script>

  • 相关阅读:
    [IDEs]Eclipse For Mac , 常用快捷键
    Songs
    [Android学习笔记]扩展application
    [Android学习笔记]Context简单理解
    Activity组件的生命周期
    [数据结构和算法]快速排序笔记
    关于项目团队管理的几点思考
    【转】一步步教你读懂NET中IL(图文详解)
    【札记】设计的五个原则
    【转】高并发情况下的单例模式
  • 原文地址:https://www.cnblogs.com/sky7034/p/2084995.html
Copyright © 2020-2023  润新知