网站sitemap.xml文件的作用主要是搜索引擎蜘蛛看的,方便蜘蛛的爬取和收录。下方代码是用c#写的生成sitemap.xml地图文件的代码,可根据实际情况修改。
/// <summary>
/// 生成SiteMap地图
/// </summary>
/// <returns></returns>
public static bool CreateSiteMapXml()
{
//先创建XML,返回路径
var xmldoc = new XmlDocument();
//加入XML的声明段落
XmlDeclaration xmldecl = xmldoc.CreateXmlDeclaration("1.0", "UTF-8", null);
xmldoc.AppendChild(xmldecl);
//加入一个根元素
XmlNode xmlelem = xmldoc.CreateElement("", "urlset", "");
//添加属性
XmlAttribute attr = xmldoc.CreateAttribute("xmlns");
attr.Value = "http://www.sitemaps.org/schemas/sitemap/0.9";
if (xmlelem.Attributes != null) xmlelem.Attributes.SetNamedItem(attr);
xmldoc.AppendChild(xmlelem);
XmlNode root = xmldoc.SelectSingleNode("urlset");//查找<urlset>
#region 根目录
XmlElement xe1 = xmldoc.CreateElement("url");//创建一个<url>节点
XmlElement xmlelem1 = xmldoc.CreateElement("", "loc", "");
XmlText xmltext = xmldoc.CreateTextNode("https://www.qizhantong.net/");
xmlelem1.AppendChild(xmltext);
xe1.AppendChild(xmlelem1);
xmlelem1 = xmldoc.CreateElement("", "lastmod", "");
xmltext = xmldoc.CreateTextNode(DateTime.Now.ToString("yyyy-MM-dd"));//最后更新日期当前的日期
xmlelem1.AppendChild(xmltext);
xe1.AppendChild(xmlelem1);
xmlelem1 = xmldoc.CreateElement("", "changefreq", "");
xmltext = xmldoc.CreateTextNode("Daily");//变化频率 设置按天更新
xmlelem1.AppendChild(xmltext);
xe1.AppendChild(xmlelem1);
xmlelem1 = xmldoc.CreateElement("", "priority", "");
xmltext = xmldoc.CreateTextNode("1.0");//首页的优先级设置为最高
xmlelem1.AppendChild(xmltext);
xe1.AppendChild(xmlelem1);
root.AppendChild(xe1);//添加到<urlset>节点中
#endregion
#region 保存文章
DataTable articleDT = null;// 这里是你的文章数据 根据你的实际情况写;
foreach (DataRow row in articleDT.Rows)
{
xe1 = xmldoc.CreateElement("url");//创建一个<url>节点
xmlelem1 = xmldoc.CreateElement("", "loc", "");
xmltext = xmldoc.CreateTextNode("https://www.qizhantong.net/" + row["id"] + ".html");
xmlelem1.AppendChild(xmltext);
xe1.AppendChild(xmlelem1);
xmlelem1 = xmldoc.CreateElement("", "lastmod", "");
xmltext = xmldoc.CreateTextNode(Utils.ObjectToDateTime(row["add_time"]).ToString("yyyy-MM-dd"));//最后更新日期为文章的添加日期
xmlelem1.AppendChild(xmltext);
xe1.AppendChild(xmlelem1);
xmlelem1 = xmldoc.CreateElement("", "changefreq", "");
xmltext = xmldoc.CreateTextNode("Daily");//变化频率 设置按天更新
xmlelem1.AppendChild(xmltext);
xe1.AppendChild(xmlelem1);
xmlelem1 = xmldoc.CreateElement("", "priority", "");
xmltext = xmldoc.CreateTextNode("0.8");//内页的优先值无需设置最高
xmlelem1.AppendChild(xmltext);
xe1.AppendChild(xmlelem1);
root.AppendChild(xe1);
}
#endregion
try
{
//然后在保存到源位置
xmldoc.AppendChild(xmlelem);
xmldoc.Save(System.Web.HttpContext.Current.Server.MapPath("/sitemap.xml"));
return true;
}
catch (Exception)
{
return false;
}
}