How to Write a Comment to a XML File with XmlTextWriter?
Comments can be sometimes very important to understand the structure of XML files. While I write code I use comments wherever I can, so that I don't have any problems to understand the code later. In this small example I will show you how you can add comments to a XML file with XmlTextWriter.
XmlTextWriterWithComments.aspx:
<%@ import namespace="System.Xml" %>
<%@ page language="C#" debug="true"%>
<script runat="server">
void page_load(object sender, System.EventArgs e){
XmlTextWriter xmlWriter = new XmlTextWriter(Server.MapPath("XmlTextWriterWithComments.xml"), null);
// Format the xml automatically to a tree structure
xmlWriter.Formatting = Formatting.Indented;
// Write root element
xmlWriter.WriteComment("Root Element");
// Write root element
xmlWriter.WriteStartElement("CategoryList");
// Category is our first sub element, we can have several Categories
xmlWriter.WriteComment("Category is our first sub element");
// Write first sub element of root element
xmlWriter.WriteStartElement("Category");
// Write ID Attribute
// First parameter is the attribute name and the second is the value
xmlWriter.WriteAttributeString("ID","0");
// Main Category can be only XML,XSL or XPath
xmlWriter.WriteComment("Main Category can be only XML,XSL or XPath");
// now start adding elements to the Category element
xmlWriter.WriteElementString("MainCategory","XML");
// Description of the Main Category
xmlWriter.WriteComment("Description of the Main Category");
// add the 2nd element to the Category element
xmlWriter.WriteElementString("Description","XML Articles");
// This can be either Yes or No
xmlWriter.WriteComment("This can be either Yes or No");
// add the 3rd element to the Category element
xmlWriter.WriteElementString("Active","Yes");
// write end elements
xmlWriter.WriteEndElement();
// close writer
xmlWriter.Close();
Response.Write("Xml Written");
}
</script>
As you can see the key to add comments is to use the function WriteComment(). You can simple pass the comment as a string and the XmlTextWriter will convert it automatically to <!--Comment-->. Nice heh? And here is the generated xml file.
XmlTextWriterWithComments.xml:
<!--Root Element-->
<CategoryList>
<!--Category is our first sub element-->
<Category ID="0">
<!--Main Category can be only XML,XSL or XPath-->
<MainCategory>XML</MainCategory>
<!--Description of the Main Category-->
<Description>XML Articles</Description>
<!--This can be either Yes or No-->
<Active>Yes</Active>
</Category>
</CategoryList>