博客系统自动生成Sitemap网址地图为了让网站内容更高的收录,建立网址地图告诉搜索引擎哪些网页想要被收录。
我的博客系统是自己写的,我需要不定时更新sitemap增加新内容,所以用代码生成sitemap是必要的,这样不用每次编辑。
sitemap就是一个xml文本,放在网站空间的根目录下,引擎蜘蛛会自动读取。
sitemap写法格式如下:
<?xml version=”1.0″ encoding=”UTF-8″?>
< urlset xmlns=http://www.google.com/schemas/sitemap/0.9>
<url>
<loc>http://www.neesoo.cn/archives/71.html</loc>
<lastmod>2009-03-07</lastmod>
<changefreq>yearly</changefreq>
<priority>0.2</priority>
</url>
<url>
<loc>http://www.neesoo.cn/archives/71.html</loc>
<lastmod>2009-03-06</lastmod>
<changefreq>yearly</changefreq>
<priority>0.2</priority>
</url>
</urlset>
loc网址(必填项),lastmod最后一次编辑的时间,changefreq跟新频率,priority权重。
部分代码如下:
[WebMethod] public string GenerateSitemap(string PassWord) { if (PassWord != "XXXXXXXXX") { return "非正规途径调用!!!!"; } else { DataSet MyBlogs = new DataSet(); string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\storage\\users.accdb"; using (OleDbConnection con = new OleDbConnection(conStr)) { string cmdStr = "select [blogUrl] from blog"; using (var cmd = new OleDbCommand(cmdStr, con)) { con.Open(); OleDbDataAdapter s = new OleDbDataAdapter(cmdStr, conStr); s.Fill(MyBlogs); con.Close(); } } urlset urlsets = new urlset(); urlsets.urls = new List<Url>(); for (int x = 0; x < MyBlogs.Tables[0].Rows.Count; x++) { Url blog = new Url() { Loc = MyBlogs.Tables[0].Rows[x][0].ToString(), Priority = 1, }; urlsets.urls.Add(blog); }; string strUploadPath = HttpContext.Current.Server.MapPath("") + "\\sitemap.xml"; using (FileStream objfilestream = new FileStream(strUploadPath, FileMode.Create, FileAccess.ReadWrite)) { XmlSerializer xmlSearializer = new XmlSerializer(typeof(urlset)); xmlSearializer.Serialize(objfilestream, urlsets); } return "ok"; } }
其中Xml类的序列化定义。
public class urlset { //[XmlAttribute("urlset")] [XmlElement(ElementName = "url")] public List<Url> urls { get; set; } } public class Url { //[XmlAttribute("loc")] [XmlElement(ElementName = "loc")] public string Loc { get; set; } //[XmlAttribute("lastmod")] [XmlElement(ElementName = "lastmod")] public string Lastmod { get; set; } //[XmlAttribute("changefreq")] [XmlElement(ElementName = "changefreq")] public string Changefreq { get; set; } //[XmlAttribute("priority")] [XmlElement(ElementName = "priority")] public int Priority { get; set; } }
(the end)