Como: Criar um arquivo de documentação XML para um aplicativo gerado pelo CodeDOM

CodeDOM pode ser usado para criar código que gera documentação XML.O processo envolve a criação de gráfico CodeDOM que contém os comentários de documentação XML, gerando o código e compilar o código gerado com opção do compilador que cria a saída de documentação XML.

Para criar um gráfico de CodeDOM que contém comentários da documentação XML

  1. Criar um CodeCompileUnit que contém o gráfico de CodeDOM para o aplicativo de exemplo.

  2. Use o CodeCommentStatement construtor com o docComment parâmetro definido como true Para criar o texto e elementos de comentário de documentação XML.

    Dim class1 As New CodeTypeDeclaration("Class1")
    
    class1.Comments.Add(New CodeCommentStatement("<summary>", True))
    class1.Comments.Add(New CodeCommentStatement( _
        "Create a Hello World application.", True))
    class1.Comments.Add(New CodeCommentStatement( _
        "<seealso cref=" & ControlChars.Quote & "Class1.Main" & _
        ControlChars.Quote & "/>", True))
    class1.Comments.Add(New CodeCommentStatement("</summary>", True))
    
    ' Add the new type to the namespace type collection.
    samples.Types.Add(class1)
    
    ' Declare a new code entry point method.
    Dim start As New CodeEntryPointMethod()
    start.Comments.Add(New CodeCommentStatement("<summary>", True))
    start.Comments.Add(New CodeCommentStatement( _
        "Main method for HelloWorld application.", True))
    start.Comments.Add(New CodeCommentStatement( _
        "<para>Add a new paragraph to the description.</para>", True))
    start.Comments.Add(New CodeCommentStatement("</summary>", True))
    

Para gerar o código a partir de CodeCompileUnit

  • Use o GenerateCodeFromCompileUnit método para gerar o código e criar um arquivo de fonte a ser compilado.

    Dim sourceFile As New StreamWriter(sourceFileName)
    
    LogMessage("Generating code...")
    provider.GenerateCodeFromCompileUnit(cu, sourceFile, Nothing)
    sourceFile.Close()
    

Para compilar o código e gerar o arquivo de documentação

  • Adicionar o /doc opção do compilador para o CompilerOptions propriedade de um CompilerParameters objeto e passar o objeto para o CompileAssemblyFromFile método para criar o arquivo de documentação XML quando o código é compilado.

    Dim opt As New CompilerParameters(New String() {"System.dll"})
    opt.GenerateExecutable = True
    opt.OutputAssembly = "HelloWorld.exe"
    opt.TreatWarningsAsErrors = True
    opt.IncludeDebugInformation = True
    opt.GenerateInMemory = True
    opt.CompilerOptions = "/doc"
    
    Dim results As CompilerResults
    
    LogMessage(("Compiling with " & providerName))
    results = provider.CompileAssemblyFromFile(opt, sourceFileName)
    

Exemplo

O exemplo de código a seguir cria um gráfico de CodeDOM com comentários de documentação, gera um arquivo de código de gráfico e compila o arquivo e cria um arquivo de documentação XML associado.

Imports System
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.IO
Imports System.Text.RegularExpressions



Class Program
    Private Shared providerName As String = "vb"
    Private Shared sourceFileName As String = "test.vb"

    Shared Sub Main(ByVal args() As String)
        Dim provider As CodeDomProvider = _
            CodeDomProvider.CreateProvider(providerName)

        LogMessage("Building CodeDOM graph...")

        Dim cu As New CodeCompileUnit()

        cu = BuildHelloWorldGraph()


        Dim sourceFile As New StreamWriter(sourceFileName)

        LogMessage("Generating code...")
        provider.GenerateCodeFromCompileUnit(cu, sourceFile, Nothing)
        sourceFile.Close()

        Dim opt As New CompilerParameters(New String() {"System.dll"})
        opt.GenerateExecutable = True
        opt.OutputAssembly = "HelloWorld.exe"
        opt.TreatWarningsAsErrors = True
        opt.IncludeDebugInformation = True
        opt.GenerateInMemory = True
        opt.CompilerOptions = "/doc"

        Dim results As CompilerResults

        LogMessage(("Compiling with " & providerName))
        results = provider.CompileAssemblyFromFile(opt, sourceFileName)

        OutputResults(results)
        If results.NativeCompilerReturnValue <> 0 Then
            LogMessage("")
            LogMessage("Compilation failed.")
        Else
            LogMessage("")
            LogMessage("Demo completed successfully.")
        End If
        File.Delete(sourceFileName)

    End Sub 'Main


    ' Build a Hello World program graph using 
    ' System.CodeDom types.
    Public Shared Function BuildHelloWorldGraph() As CodeCompileUnit
        ' Create a new CodeCompileUnit to contain 
        ' the program graph.
        Dim compileUnit As New CodeCompileUnit()

        ' Declare a new namespace called Samples.
        Dim samples As New CodeNamespace("Samples")
        ' Add the new namespace to the compile unit.
        compileUnit.Namespaces.Add(samples)

        ' Add the new namespace import for the System namespace.
        samples.Imports.Add(New CodeNamespaceImport("System"))

        ' Declare a new type called Class1.
        Dim class1 As New CodeTypeDeclaration("Class1")

        class1.Comments.Add(New CodeCommentStatement("<summary>", True))
        class1.Comments.Add(New CodeCommentStatement( _
            "Create a Hello World application.", True))
        class1.Comments.Add(New CodeCommentStatement( _
            "<seealso cref=" & ControlChars.Quote & "Class1.Main" & _
            ControlChars.Quote & "/>", True))
        class1.Comments.Add(New CodeCommentStatement("</summary>", True))

        ' Add the new type to the namespace type collection.
        samples.Types.Add(class1)

        ' Declare a new code entry point method.
        Dim start As New CodeEntryPointMethod()
        start.Comments.Add(New CodeCommentStatement("<summary>", True))
        start.Comments.Add(New CodeCommentStatement( _
            "Main method for HelloWorld application.", True))
        start.Comments.Add(New CodeCommentStatement( _
            "<para>Add a new paragraph to the description.</para>", True))
        start.Comments.Add(New CodeCommentStatement("</summary>", True))
        ' Create a type reference for the System.Console class.
        Dim csSystemConsoleType As New CodeTypeReferenceExpression( _
            "System.Console")

        ' Build a Console.WriteLine statement.
        Dim cs1 As New CodeMethodInvokeExpression(csSystemConsoleType, _
            "WriteLine", New CodePrimitiveExpression("Hello World!"))

        ' Add the WriteLine call to the statement collection.
        start.Statements.Add(cs1)

        ' Build another Console.WriteLine statement.
        Dim cs2 As New CodeMethodInvokeExpression(csSystemConsoleType, _
            "WriteLine", New CodePrimitiveExpression( _
            "Press the ENTER key to continue."))

        ' Add the WriteLine call to the statement collection.
        start.Statements.Add(cs2)

        ' Build a call to System.Console.ReadLine.
        Dim csReadLine As New CodeMethodInvokeExpression( _
            csSystemConsoleType, "ReadLine")

        ' Add the ReadLine statement.
        start.Statements.Add(csReadLine)

        ' Add the code entry point method to
        ' the Members collection of the type.
        class1.Members.Add(start)

        Return compileUnit

    End Function 'BuildHelloWorldGraph

    Shared Sub LogMessage(ByVal [text] As String)
        Console.WriteLine([text])

    End Sub 'LogMessage


    Shared Sub OutputResults(ByVal results As CompilerResults)
        LogMessage(("NativeCompilerReturnValue=" & _
            results.NativeCompilerReturnValue.ToString()))
        Dim s As String
        For Each s In results.Output
            LogMessage(s)
        Next s

    End Sub 'OutputResults
End Class 'Program

O exemplo de código cria a seguinte documentação XML no arquivo HelloWorldDoc.xml.

<?xml version="1.0" ?> 
<doc>
  <assembly>
    <name>HelloWorld</name> 
  </assembly>
  <members>
    <member name="T:Samples.Class1">
      <summary>
        Create a Hello World application. 
        <seealso cref="M:Samples.Class1.Main" /> 
      </summary>
    </member>
    <member name="M:Samples.Class1.Main">
      <summary>
        Main method for HelloWorld application. 
        <para>Add a new paragraph to the description.</para> 
      </summary>
    </member>
  </members>
</doc>

Compilando o código

  • Este exemplo de código requer a FullTrust conjunto permissão para executar com êxito.

Consulte também

Conceitos

Documentando Seu Código com XML (Visual Basic)

Referência

Comentários de documentação XML (Guia de programação C#)

Outros recursos

Documentação XML (Visual C++)