XComment

In this chapter you will learn:

  1. Creating a Comment and Adding It to Its Element
  2. Add a comment to XDocument

Creating a Comment and Adding It to Its Element

using System;//from j  av a  2s. c  om
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
public class MainClass {
    public static void Main() {

        XElement myXML = new XElement("Book"); 
        XComment xComment = new XComment("This person is retired.");
        myXML.Add(xComment);

        Console.WriteLine(myXML);

    }
}

Add a comment to XDocument

using System;//j av a  2  s .  c  o m
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.IO;


public class MainClass{

   public static void Main(string[] args){   
      XDocument NewDoc = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),
            new XElement("Root", "MyDoc"));  
      // Add a comment.
      NewDoc.AddFirst(new XComment("This is a comment."));

      // Add another comment.
      NewDoc.Element("Root").Add(new XComment("This is another comment."));

      // Add a third comment.
      NewDoc.Add(new XComment("This is the third comment."));

      // Add some text.
      NewDoc.Element("Root").Add(new XText("This is some text."));
   }
}

Next chapter...

What you will learn in the next chapter:

  1. Creating a Declaration
Home » C# Tutorial » XML Linq
XDocument
Create XDocument
Add to XDocument
Parse XML file with XDocument
Load XML string with XDocument
XDocument Root
Query XML document with Linq
Save XML document
XDocument Serialize
XElement namespace
Adding attribute
XElement's NextNode
XAttribute
XAttribute value
XAttribute Properties
XAttribute namespace
XComment
XDeclaration
XML declaration
XCData
XNamespace