Use .NET to Add Comment to XML - C# / XmlSerializer / XmlDocument

See related: .NET examples

First, learn how to use the .NET XmlSerializer class.

To add a comment to XML using the XmlSerializer and XmlDocument classes, create a class that inherits from StringWriter and overrides the Encoding to make it UTF-8 as this is typical for XML. Next, create a XmlSerializer then serialize a class and load the serialized data into a new XmlDocument, create a new comment (XmlComment) insert it into the document (the XML document element in this example) and then save the document to an new StringWriterUtf8.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace XmlExample
{
	public class StringWriterUtf8 : StringWriter
	{
		public override Encoding Encoding => Encoding.UTF8;
	}

	[Serializable]
	[XmlRoot("node")]
	[XmlType("node")]
	public class Node
	{
		[XmlElement("name")]
		public string Name { get; set; }

	}

	[Serializable]
	[XmlRoot(ElementName = "foobar", Namespace = "")]
	public class FooBar : List<Node>
	{
		public string ToXml()
		{
			var serializer = new XmlSerializer(typeof(FooBar));

			using (var writer = new StringWriterUtf8())
			{
				serializer.Serialize(writer, this);

				XmlDocument doc = new XmlDocument();
				doc.LoadXml(writer.ToString());

				XmlComment newComment;
				newComment = doc.CreateComment("  This comment added by prowaretech.com  ");

				XmlElement root = doc.DocumentElement;
				doc.InsertBefore(newComment, root);

				using (var sr = new StringWriterUtf8())
				{
					doc.Save(sr);
					return sr.ToString();
				}
			}
		}

	}
}

Using the above example:

using System;
using System.IO;

namespace ConsoleApp1
{
	class Program
	{
		static void Main(string[] args)
		{
			var fb = new XmlExample.FooBar();
			fb.Add(new XmlExample.Node { Name = "Node1" });
			Console.Write(fb.ToXml());
		}
	}
}

The output should look like this:

<?xml version="1.0" encoding="utf-8"?>
<!--  This comment added by prowaretech.com  -->
<foobar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <node>
    <name>Node1</name>
  </node>
</foobar>

Coding Video

https://youtu.be/HG8VOxTv5sI


Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site.
OK