sitemap.xmlの作り方

検索エンジン用のsitemap.xmlの実装例です。指定したフォルダ以下にアップロードするファイル一式が揃っている状態で使用します。携帯電話向けのsitemap.xmlも出力することができます。


Imports System
Imports System.Xml
Imports System.Text

Public Class xmlUtils

Public Const CS_WAIT_TIME As Integer = 1000

Public Enum SitemapType
SitemapPc
SitemapMobile
End Enum

Public Shared Sub BuildSiteMapXml(ByVal folderPath As String, ByVal baseUrl As String, ByVal SitemapType As SitemapType)

Dim urlList As List(Of String) = PathUtils.GetFileList(folderPath, True)
Dim siteMapBuilder As New StringBuilder

siteMapBuilder.AppendLine("")

If SitemapType = xmlUtils.SitemapType.SitemapPc Then
siteMapBuilder.AppendLine("")
Else
siteMapBuilder.AppendLine("")
End If

Dim replaceFolderPath As String = folderPath
Dim replaceBaseUrl As String = baseUrl

If (replaceFolderPath.Substring(replaceFolderPath.Length - 1, 1) <> "\") AndAlso _
(replaceBaseUrl.Substring(replaceBaseUrl.Length - 1, 1) = "/") Then

replaceFolderPath += "\"

End If

If (replaceFolderPath.Substring(replaceFolderPath.Length - 1, 1) = "\") AndAlso _
(replaceBaseUrl.Substring(replaceBaseUrl.Length - 1, 1) <> "/") Then

replaceBaseUrl += "/"

End If

For i As Integer = 0 To urlList.Count - 1

Dim url As String = String.Empty

url = urlList(i)

Dim fileName As String = System.IO.Path.GetFileName(url)
If fileName = "robots.txt" Then
Continue For
End If

If fileName = "sitemap.xml" Then
Continue For
End If

Dim ext As String = System.IO.Path.GetExtension(url)
If (ext = "html") Or (ext = "htm") Or (ext = "php") Then
Continue For
End If

url = url.Replace(replaceFolderPath, replaceBaseUrl)
url = url.Replace("\", "/")

Dim lastMod As String = String.Empty

lastMod = Date.Now.ToString("yyyy-MM-dd") + "T" + Date.Now.ToString("hh:mm:ss") + "+09:00"

siteMapBuilder.AppendLine("")
siteMapBuilder.AppendLine("" + url + "")
siteMapBuilder.AppendLine("" + lastMod + "")

If SitemapType = xmlUtils.SitemapType.SitemapPc Then
siteMapBuilder.AppendLine("daily")
Else
siteMapBuilder.AppendLine("")
End If

siteMapBuilder.AppendLine("")

Next

siteMapBuilder.AppendLine("")

Dim filePath As String = String.Empty
filePath = System.IO.Path.Combine(folderPath, "sitemap.xml")
System.IO.File.WriteAllText(filePath, siteMapBuilder.ToString)

Dim robotText As String = "Sitemap :" + replaceBaseUrl + "sitemap.xml" + vbCrLf
filePath = System.IO.Path.Combine(folderPath, "robots.txt")
System.IO.File.WriteAllText(filePath, robotText)

End Sub

End Class