Web.sitemap自动生成教程(值得珍藏)“绝对是好东西”

 
查看文章
   
Web.sitemap自动生成教程(值得珍藏)“绝对是好东西”
2009年11月21日 下午 10:04

      相信大家在创建Web.sitemap的时候手动输入时都很头疼,以下方法可以解决需要手动输入的问题。但是生成的Web.sitemap会遍历了整个网站文件及目录(asp.net的appcode等文件夹除外),只需要稍作修改即可,可比一个个手动输入省力得多了,值得珍藏

具体操作方法:

新建一个记事本,把以下代码另存为“SiteMapModule.vb”

======================从这里开始复制代码,本行不复制========================

Option Explicit On
Option Strict On

Imports System
Imports System.IO
Imports System.Xml
Imports EnvDTE

Public Module SiteMapModule

    ' the name for your sitemap file
    Private ReadOnly sitemapFileName As String = "web.sitemap"

    ' macro will only insert a siteMapNode for files with the following extensions
    Private ReadOnly validSiteMapNodes() As String = {".ASPX", ".HTML", ".HTM"}

    ' macro will skip directories starting with these strings
    Private ReadOnly excludeDirectoriesPrefix() As String = {"APP_", "BIN", "PROPERTIES"}


    Public Sub CreateWebSitemap()

        Dim processed As Integer = 0

        For Each project As EnvDTE.Project In DTE.Solution.Projects

            If IsWebProject(project) Then

                If HasValidStartPage(project) Then

                    ProcessWebSite(project)
                    processed = processed + 1

                Else

                    MsgBox(project.Name + " - You must first select a start page using solution explorer.")

                End If
            End If
        Next

        MsgBox("Processed " + processed.ToString() + " web project(s)")

    End Sub


    Private Sub ProcessWebSite(ByVal project As EnvDTE.Project)

        If HasExistingSiteMap(project) Then
            MsgBox(project.Name + " already has a file named " + sitemapFileName)
            Return
        End If

        CreateSiteMap(project)

        Dim parent As XmlNode = SetSiteMapRoot(project)
        CreateNodes("", parent, project.ProjectItems)

        siteMap.Save(Path.Combine(project.Properties.Item("FullPath").Value.ToString, sitemapFileName))

    End Sub


    Private Function IsWebProject(ByVal project As EnvDTE.Project) As Boolean

        If project.Kind.ToUpper() = webSiteProjectGuid Then
            isWebAppProject = False
            Return True
        End If

        If project.Kind.ToUpper() = webAppProjectGuid Then
            isWebAppProject = True
            Return True
        End If

        Return False

    End Function

    Private Function GetProjectStartPage(ByVal project As EnvDTE.Project) As String

        Dim result As String = Nothing

        Dim indexer As String = webSiteStartPage
        If isWebAppProject Then
            indexer = webAppStartPage
        End If

        If project.Properties.Item(indexer) Is Nothing Then
            result = Nothing
        Else
            result = project.Properties.Item(indexer).Value.ToString()
        End If

        Return result

    End Function

    Private Function HasValidStartPage(ByVal project As EnvDTE.Project) As Boolean

        Dim startPage As String = GetProjectStartPage(project)

        If startPage Is Nothing OrElse startPage.Length < 1 Then
            Return False
        End If

        Return True

    End Function

    Private Function SetSiteMapRoot(ByVal project As EnvDTE.Project) As XmlNode

        Dim startPage As String = GetProjectStartPage(project)
        startUrl = startPage
        Dim root As XmlNode = CreateSiteMapNode(startPage, DeriveTitle(startPage))
        siteMap.DocumentElement.AppendChild(root)

        Return root

    End Function

    Private Sub CreateNodes(ByVal itemPath As String, ByVal parent As XmlNode, ByVal items As EnvDTE.ProjectItems)

        Dim node As XmlNode

        For Each item As EnvDTE.ProjectItem In items

            If IsValidFile(item) Then

                Dim url As String = UrlCombine(itemPath, item.Name)
                If url <> startUrl Then
                    node = CreateSiteMapNode(UrlCombine(itemPath, item.Name), DeriveTitle(item.Name))
                    parent.AppendChild(node)
                End If

            ElseIf IsValidDirectory(item) Then

                node = CreateSiteMapNode(Nothing, item.Name)
                parent.AppendChild(node)
                CreateNodes(UrlCombine(itemPath, item.Name), node, item.ProjectItems)

            End If

        Next

    End Sub

    Private Function IsValidDirectory(ByVal item As EnvDTE.ProjectItem) As Boolean

        If item.ProjectItems Is Nothing Then
            Return False
        Else
            For Each name As String In excludeDirectoriesPrefix
                If item.Name.ToUpper().StartsWith(name) Then
                    Return False
                End If
            Next
        End If

        ' for WAP, it seems all project items have a non-null ProjectItems property
        ' (even .cs files). check to see if the directory exists on disk
        Dim fullPath As String
        fullPath = item.Properties.Item("FullPath").Value.ToString()
        If Not String.IsNullOrEmpty(fullPath) Then
            If Not Directory.Exists(fullPath) Then
                Return False
            End If
        End If

        Return True

    End Function

    Private Function IsValidFile(ByVal item As EnvDTE.ProjectItem) As Boolean

        For Each name As String In validSiteMapNodes
            If item.Name.ToUpper().EndsWith(name) Then
                Return True
            End If
        Next

        Return False

    End Function

    Private Function UrlCombine(ByVal path1 As String, ByVal path2 As String) As String

        If path1 = String.Empty Then
            Return path2
        End If

        If Not path1.EndsWith("/") Then
            path1 = path1 + "/"
        End If

        Return path1 + path2

    End Function

    Private Function CreateSiteMapNode(ByVal url As String, ByVal title As String) As XmlElement

        Dim node As XmlElement
        node = siteMap.CreateElement("siteMapNode", SitemapSchema)

        If Not url Is Nothing Then
            Dim urlAttr As XmlAttribute = siteMap.CreateAttribute("url")
            urlAttr.Value = url
            node.Attributes.Append(urlAttr)
        End If

        Dim titleAttr As XmlAttribute = siteMap.CreateAttribute("title")
        titleAttr.Value = title
        node.Attributes.Append(titleAttr)

        Return node

    End Function

    Private Function DeriveTitle(ByVal fileName As String) As String
        Return Path.GetFileNameWithoutExtension(fileName)
    End Function

    Private Function CreateSiteMap(ByVal project As EnvDTE.Project) As XmlDocument

        siteMap = New XmlDocument()
        siteMap.AppendChild(siteMap.CreateXmlDeclaration("1.0", "utf-8", Nothing))
        siteMap.AppendChild(siteMap.CreateElement("siteMap", SitemapSchema))

        nsMgr = New XmlNamespaceManager(siteMap.NameTable)
        nsMgr.AddNamespace("s", SitemapSchema)

        Dim filename As String = Path.Combine(project.Properties.Item("FullPath").Value.ToString, sitemapFileName)
        siteMap.Save(filename)
        project.ProjectItems.AddFromFile(filename)

        Return siteMap

    End Function

    Private Function HasExistingSiteMap(ByVal project As EnvDTE.Project) As Boolean

        For Each item As EnvDTE.ProjectItem In project.ProjectItems
            If item.Name.ToLower() = sitemapFileName Then
                If MsgBox("Overwrite existing sitemap file?", MsgBoxStyle.YesNo) = MsgBoxResult.No Then
                    Return True
                End If
            End If
        Next

        Return False

    End Function

    Private siteMap As XmlDocument
    Private nsMgr As XmlNamespaceManager
    Private startUrl As String
    Private Const SitemapSchema As String = "http://schemas.microsoft.com/AspNet/SiteMap-File-1.0"
    Private isWebAppProject As Boolean


    ' these seem to be the secret numbers for web projects in 2005
    Private ReadOnly webSiteProjectGuid As String = "{E24C65DC-7377-472B-9ABA-BC803B73C61A}"
    Private ReadOnly webAppProjectGuid As String = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"

    'these string index into project properties to fetch the start page URL
    Private ReadOnly webSiteStartPage As String = "StartPage"
    Private ReadOnly webAppStartPage As String = "WebApplication.StartPageUrl"

End Module

======================结束代码复制,本行不复制========================

打开 Visual Studio

1、按Alt-F8把Macro Explorer调出来


2、在Macros上点右键,选择“Macros IDE...”


3、在“MyMacros”工程(或者你自己的Macro工程)里“Add References”,把System.XML.dll加进来


4、“Add Existing Item”,把从上面创建的“SiteMapModule.vb”文件添加进来。


5、关闭Macros IDE,回到Macro Explorer。MyMacros下面的新增了你刚才添加的macro module:“SiteMapModule”,其下有一个Macro:“CreateWebSitemap” 。右键点击这个macro,选择“Run”。


这样Web.sitemap文件就生成出来了。

posted @ 2011-11-23 08:15  gaoxuzhao  阅读(1160)  评论(0编辑  收藏  举报