用XmlTextWriter类创建xml文件

in Develop

原来在写xml时总是用StringBuilder的Append方法进行拼凑
现在的rss就是用xmlTextWriter类来实现
看具体的例子:
需要引用System.Text和System.Xml名称空间

StringBuilder sb = new StringBuilder();
        using (XmlTextWriter xw = new XmlTextWriter(new StringWriter(sb)))
        {
            xw.WriteProcessingInstruction("xml", @"version=""1.0"" encoding=""utf-8""");
            xw.WriteStartElement("rss");
            xw.WriteAttributeString("version", "2.0");
            xw.WriteStartElement("channel");
            xw.WriteElementString("title", "幻想曲.Net");

            xw.WriteElementString("description", "幻想曲.Net:专注于.Net技术!");
            xw.WriteElementString("link", "http://yibin.us");
            xw.WriteElementString("language", "zh-cn");
            xw.WriteElementString("generator", "yibin.us");
            xw.WriteElementString("WebMaster", "幻想曲.Net");
            xw.WriteStartElement("image");
            xw.WriteElementString("title", "幻想曲.Net - 专注于.Net技术");
            xw.WriteElementString("url","http://yibin.us");
            xw.WriteElementString("logo", "http://yibin.us/logo.gif");
            xw.WriteEndElement();
            string _strsql = "select top 15 documentid,subject,content,publishdate,categoryname from documents order by documentid desc";
            using (SqlConnection conn = new SqlConnection(_connstr))
            {
                SqlCommand comm = new SqlCommand(_strsql, conn);
                conn.Open();
                using (SqlDataReader r = comm.ExecuteReader())
                {
                    while (r.Read())
                    {
                        xw.WriteStartElement("item");
                        xw.WriteElementString("title", (string)r["subject"]);
                        xw.WriteElementString("link", "http://yibin.us/zh-cn/item," + r["documentid"].ToString() + ".html");
                        xw.WriteElementString("category", r["categoryname"].ToString());
                        xw.WriteElementString("author", "幻想曲.Net");
                        xw.WriteElementString("pubdate", r["publishdate"].ToString());
                        xw.WriteElementString("guid", "http://yibin.us/zh-cn/item," + r["documentid"].ToString() + ".html");
                        xw.WriteElementString("description", "");

                        xw.WriteEndElement();
                    }
                }
            }
            xw.WriteEndElement();
            xw.WriteEndElement();
        }

具体的方法可参阅msdn文档,这里就不冗述了

0 Comments

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>