Vs宏 之 整理HTML文档格式

有时从其它HTML编辑器得到的 HTML 是非标准的。一些标签没有闭合。不影响功能,但VS会提示不正确,而且,不能正常的缩进。如: input , br ,meta .

以下宏做两件事情:

1. 修正没有闭合的标签

2.把编码转为 UTF8

 其中:宏所引用的Dll路径: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies

 取得解决方案选中项: 

DirectCast(DTE.SelectedItems.Item(1).ProjectItem, EnvDTE.ProjectItem).Properties.Item("FullPath").Value

    '补全自闭合标签。像 input br meta
    Sub TidyHtmlSolo()

        For i As Integer = 1 To DTE.SelectedItems.Count
            Dim fileName = DirectCast(DTE.SelectedItems.Item(i).ProjectItem, EnvDTE.ProjectItem).Properties.Item("FullPath").Value


            If (System.IO.Directory.Exists(fileName)) Then

                Dim fs = System.IO.Directory.GetFiles(fileName, "*.aspx", SearchOption.AllDirectories)

                For j As Integer = 0 To fs.Length - 1

                    TidyOneHtmlSolo(fs(j))

                Next
            ElseIf (System.IO.File.Exists(fileName)) Then
                TidyOneHtmlSolo(fileName)
            Else
                MsgBox("找不到文件:" + fileName)
                Exit Sub
            End If

        Next
    End Sub

    Function TidyOneHtmlSolo(ByVal fileName As String)
        If (File.Exists(fileName) = False) Then
            MsgBox("找不到文件:" + fileName)
            Exit Function
        End If

        Dim txt = File.ReadAllText(fileName, System.Text.Encoding.Default)

        Dim html = New HtmlCharLoad(txt)
        Dim list = html.Load(HtmlNodeProc.ProcType.None)


        For i As Integer = 0 To list.Count - 1
            Dim o = list(i)
            If o.Type = HtmlNode.NodeType.Tag Then
                Dim tag = CType(o, HtmlTagNode)
                If tag.TagName.ToLower().IsIn(New String() {"input", "br", "meta", "link"}) Then
                    If (tag.IsSole = False And i < list.Count - 1) Then
                        Dim n = list(i + 1)
                        If (n.Type <> HtmlNode.NodeType.CloseTag) Then
                            tag.IsSole = True
                        End If
                    End If
                End If
            End If
        Next


        File.WriteAllText(fileName, String.Join("", list.Select(Function(a) a.ToString()).ToArray()), System.Text.Encoding.UTF8)
    End Function

posted @ 2012-11-23 13:54  NewSea  阅读(979)  评论(0编辑  收藏  举报