Programmatically get Summary comments at runtime

Riaan Walters picture Riaan Walters · Mar 24, 2013 · Viewed 34.2k times · Source

I'm looking for a way to programmatically get the summary portion of Xml-comments of a method in ASP.net.

I have looked at the previous related posts and they do not supply a way of doing so in a web environment.

I can not use any 3rd party apps and due to a web environment, Visual studio plugin's aren't much use either.

The closest thing I have found to a working solution was the JimBlackler project, but it only works on DLL's.

Naturally, something like 'supply .CS file, get XML documentation' would be optimal.


Current situation

I have a web-service and trying to dynamically generate documentation for it.

Reading the Methods, and properties is easy, but getting the Summary for each method is throwing me off a bit.

/// <summary>
/// This Is what I'm trying to read
/// </summary>
public class SomeClass()
{
    /// <summary>
    /// This Is what I'm trying to read
    /// </summary>
    public void SomeMethod()
    {
    }
}

Answer

Joe Frank picture Joe Frank · Dec 26, 2013

A Workaround - Using reflection on Program.DLL/EXE together with Program.XML file

If you take a look at the sibling .XML file generated by Visual Studio you will see that there is a fairly flat hierarchy of /members/member. All you have to do is get hold on each method from your DLL via MethodInfo object. Once you have this object you turn to the XML and use XPATH to get the member containing the XML documentation for this method.

Members are preceded by a letter. XML doc for methods are preceded by "M:" for class by "T:" etc.

Load your sibling XML

string docuPath = dllPath.Substring(0, dllPath.LastIndexOf(".")) + ".XML";

if (File.Exists(docuPath))
{
  _docuDoc = new XmlDocument();
  _docuDoc.Load(docuPath);
}

Use this xpath to get the member representing the method XML docu

string path = "M:" + mi.DeclaringType.FullName + "." + mi.Name;

XmlNode xmlDocuOfMethod = _docuDoc.SelectSingleNode(
    "//member[starts-with(@name, '" + path + "')]");

Now scan childnodes for all the rows of "///" Sometimes the /// Summary contains extra blanks, if this bothers use this to remove

var cleanStr = Regex.Replace(row.InnerXml, @"\s+", " ");