Does the term “XML comments” confuse you? Well, rest assured. You’re not alone. “Does that refer to comments inside an XML file?” you might wonder. Or maybe you have this vague notion that it has something to do with some kind of documentation for programming source code. Both assumptions are kind of right. But you’re still reading this post, which means that “kind of” isn’t going cut for you, right?
So this post is all about XML comments. You’re going to learn what this term actually means, what XML comments are (and aren’t) good for, and learn a thing or two about software documentation. If you’re ready, then let’s get started!
XML Comments: A Bottom-Up Definition
If the expression “XML comments” doesn’t ring a bell, one of the possible reasons is that you aren’t familiar with the individual terms “XML” and “comments” themselves. So we’ll start by eliminating that source of confusion, breaking the term down, and defining each word individually. Yes, we’ll assume a beginner level for this section, so feel free to skip it in case you’re comfortable with the definitions of both XML and comments.
XML
I think the first time I heard about XML was when someone told me it was “kind of like HTML, but you create your own tags.” While that’s a way to put it, we definitely need more for a definition.
So for starters, XML stands for “eXtensible Markup Language.” Like HTML, XML is a markup language. It makes use of special marks called “tags” to annotate parts of the text in order to give it a special meaning or other attributes. Unlike HTML, XML doesn’t come with a fixed set of available tags. Instead, you create the tags you need to represent the document or data structure you want to encode. As long as the XML is well-formed, you’re good to go.
Comments
Comments in our context refer to comments in a programming language. And what are those? In short, comments are pieces of text that you include in your source code but aren’t really programming instructions. They’re ignored by the compiler or interpreter. Their only purpose is to give some information to the future readers of your code.
Wrapping It Up
We now have both “XML” and “comments” out of the way. So how can we bring the two words together in a way that makes sense? As I see it, “XML Comments” might mean only two possible things:
- Comments inside an XML document;
- Comments in a programming language that somehow employs the XML format.
We’ll now cover each one of the possibilities above.
XML Comments as in “Comments Inside an XML Document”
Let’s say you have the following XML document:
<?xml version="1.0" encoding="UTF-8"?> <beatles> <beatle> <name>John</name> <instrument>Guitar</instrument> </beatle> <beatle> <name>George</name> <instrument>Guitar</instrument> </beatle> <beatle> <name>Paul</name> <instrument>Bass</instrument> </beatle> <beatle> <name>Ringo</name> <instrument>Drums</instrument> </beatle> </beatles>
Now, imagine you need to insert a message between the second and third items to give the user some more details. That’s how you’d do it, using a single-line comment.
<?xml version="1.0" encoding="UTF-8"?> <beatles> <beatle> <name>John</name> <instrument>Guitar</instrument> </beatle> <beatle> <name>George</name> <instrument>Guitar</instrument> </beatle> <beatle> <name>Paul</name> <instrument>Bass</instrument> </beatle> <beatle> <!-- the next guy has got blisters on his fingers! --> <name>Ringo</name> <instrument>Drums</instrument> </beatle> </beatles>
And what would you do in order to cause the XML interpreter to ignore an excerpt of the document? That answer is also to employ the multi-line comment style.
<?xml version="1.0" encoding="UTF-8"?> <beatles> <!-- <beatle> <name>John</name> <instrument>Guitar</instrument> </beatle> <beatle> <name>George</name> <instrument>Guitar</instrument> </beatle> --> <beatle> <name>Paul</name> <instrument>Bass</instrument> </beatle> <beatle> <!-- the next guy has got blisters on his fingers! --> <name>Ringo</name> <instrument>Drums</instrument> </beatle> </beatles>
Notice that, even though we employed comments to ignore two items in our XML document, the resulting text is still a valid, well-formed XML document. For instance, the following document would be considered invalid:
<?xml version="1.0" encoding="UTF-8"?> <beatles> <!-- <beatle> <name>John</name> <instrument>Guitar</instrument> </beatle> <beatle> <name>George</name> <instrument>Guitar</instrument> --> </beatle> <beatle> <name>Paul</name> <instrument>Bass</instrument> </beatle> <beatle> <!-- the next guy has got blisters on his fingers! --> <name>Ringo</name> <instrument>Drums</instrument> </beatle> </beatles>
In the example above, we have a closing tag with no matching opening one, which renders the document not well-formed.
XML Comments Rules
We’re now going to cover the rules you have to follow when working with XML comments. They are just four of them.
You Can’t Place a Comment Before the XML Declaration
First of all, you can’t place a comment before the XML declaration. The XML declaration is usually what comes first in an XML file. Even though the XML declaration isn’t required in the 1.0 version of XML, when you do include it, it has to be the first thing that appears in the file.
The implication of this rule is that you can’t place a comment before the XML declaration.
You Can’t Put a Comment Within Attribute Values
Like the first one, the second rule is also a restriction. It says you’re not allowed to place a comment within the value of an attribute. So, the following excerpt of XML would be invalid:
<name RealName="Richard Starkey <!-- invalid comment -->">Ringo</name>
Comments Cannot Be Nested Inside Other Comments
This one is pretty self-explanatory: nested XML comments aren’t allowed.
Excepting The Places In The Rules Above, Comments May Appear Anywhere In an XML Document
The last rule is a logical consequence of the previous ones. That is, as long as you don’t try to put a comment before an XML declaration, inside the value of an attribute or inside another comment, you should be fine.
XML Comments as in “API Documentation in XML Format”
API documentation is a very valuable tool for any software team. Yes, code that’s clean, concise, and self-explanatory might go a long way, but often dedicated documentation is needed. And that’s especially true for code that’s used by third-parties, such as libraries and frameworks. Some languages/platforms end up designing their own formats for API documentation. That’s the case, for instance, with Java and its Javadoc.
While that’s a legitimate choice to make, it’s also possible to use a pre-existing, widespread format. XML is a nice format in which to write documentation for classes, methods, and other software artifacts. That’s the path C#/.NET takes. And how would you go about that?
Easy. With Visual Studio open, position the cursor above any member, press the forward slash key three times, and Visual Studio will automatically create a template for you to fill in. So, let’s say you’ve got the following method:
public int Add(int a, int b) { return a + b; }
After positioning the caret above the “Add” method and pressing the forward slash key three times in a row, this is what VS will generate for you:
/// <summary> /// /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public int Add(int a, int b) { return a + b; }
From now on, you’d just have to fill the template up. First, you’d type a general summary for the method, followed by the documentation for the two parameters. Finally, you’d document the return value.
Keep in mind that the tags above aren’t the only XML documentation tags in C#; there are many more. But in the next section, we’ll cover some of the most common XML tags you’re likely to use most often in your day-to-day documentation tasks.
A Quick Example
Suppose we’re writing an application to manage a school and now we needed to create a search method for the StudentRepository class.
public IEnumerable<Student> FindByLastName(string lastName) { if (lastName == null) throw new ArgumentNullException(); if (string.Trim() == string.Empty) throw new ArgumentException(message: "Last name must be a valid, non-empty string!"); // the rest of the code is omitted due to brevity }
As you can see, the code above contains a method that searches students according to their last names. I’ve omitted the part of the method that would actually do something, for brevity. However, that doesn’t matter for the purposes of our example. In regards to members documentation, the important part is the public interface rather than the internal implementation. Let’s continue.
Starting With a Documentation Stub
We’re now going to use XML documentation tags to create code documentation for the method in the example above. Put the cursor above the method and press the forward slash key 3 times in a row and Visual Studio will place the following documentation above the method:
/// <summary> /// /// </summary> /// <param name="lastName"></param> /// <returns></returns>
Let’s now explain each one of the tags you see in the example above.
The <summary> Tag
The <summary> tag allows you to provide a brief description of what that member does. You should write a summary that is as descriptive and clear as possible and remains in the simple present tense.
The <param> Tag
The <param> tag allows you to inform not only the description of the parameter but also its name, through the “name” attribute.
The System.String instance that represents the ISBN of the book to search for.
The <returns> Tag
The <returns> tag is meant to describe the return value of your method. Besides describing what should be returned when everything goes well, it’s also helpful to describe what happens in the “sad” path scenarios. For instance, let’s say that if the method can’t find any student with the specific last name, it returns an empty IEnumerable. You should certainly include such information in the text for the <returns> tag.
The Complete Example
Take a look at the finished example with all the tags filled:
/// <summary> /// Searches and returns the students with the specified last name. /// </summary> /// <param name="lastName">The <see cref="System.String"/> instance that represents the last name of the student(s) we want to find.</param> /// <returns>A <see cref="IEnumerable{Student}"/> that contains the found students witht he specified last name. It might be empty. </returns>
The finished example contains some additional tags. Additionally, there are more tags we could’ve added. There’s a <exception> tag which would’ve made sense to add since the method in the example throws in some scenarios. But we will be covering neither of those since we already have posts that cover XML documentation tags in more depth.
With that out of the way, let’s continue. What is the reasoning behind using XML comments of either type? That’s what you’re going to see in the next section.
XML Comments: What Are They Good For?
Now you know about the two types of XML comments, but maybe you’re still wondering whether there’s any value to be found in any of them. For the first type of comment, the value proposition is clear. Commenting out one or more lines of a document enables the developer to quickly disable some lines in order to test or debug a hypothesis.
In regards to the second category, I’d say the value proposition is even clearer. Software documentation is a must, regardless of company size, team experience, or any other factor. Start documenting your APIs as soon as possible!
If you write C#, then XML documentation tags are definitely the way to go. They offer you an easy, ubiquitous, standard, and low-friction way of documenting your classes and methods. You can even employ tools to automatically generate a starting point for your documentation, based on the names and types of your methods and their parameters.
Back to You
In this post, we walked you through the definition of a somewhat confusing term. We broke it down into its component parts, defining each one individually before bringing them together again. Then, we proceeded to explain what the term might mean, showing examples of usage under both meanings.
Even though this post wasn’t meant to offer a canonical definition of “XML comments,” I hope we’ve been able to shed some light on the topic. Hopefully, you now understand at least a little bit more about software documentation and feel inspired to start documenting your software artifacts right away.
Thank you for reading. See you next time!
Learn how GhostDoc can help to simplify your XML Comments, produce and maintain quality help documentation, generate IntelliSense documentation.