CSharp - Creating Declarations with XDeclaration

Introduction

XML declarations are implemented with the XDeclaration class.

Declarations are meant to be added to an XML document, not an element.

Demo

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

class Program//from  w w w.  j av a  2  s .c  o m
{
    static void Main(string[] args){
         XDocument xDocument = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
                                    new XElement("Book"));

         Console.WriteLine(xDocument);
    }
}

Result

ToString method will omit the declaration.

If you debug the code and put a watch on the document, you will see that the declaration is there.

Related Topics