C#動態產生XML並在前台用javascript讀取

來源:互聯網
上載者:User

考慮到網站首頁使用動態網頁面的話會影響伺服器效能,所以採用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>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.