How to use XML Namespaces with XNamespace class in C#

You can use the XNamespace class to create XML content that uses a namespace. You can find more information about XML namespaces from the article How to use XML Namespaces in XML document. When you want to use XNamespace class you should define an XNamespace object first. Then you should add this XNamespace object to the beginning of the element name every time you create an XElement (or an XAttribute) that you want to place in that namespace. Here’s an example:


XNamespace ns = “”;

XDocument doc = new XDocument(

new XDeclaration(“1.0”, “utf-8”, “yes”),

new XComment(“Created with the XDocument class.”),

new XElement(ns + “BooksList”,

new XElement(ns + “Book”,

new  XAttribute(“ISBN-13”, “978-0545139700),

new XAttribute(“Title”, “Harry Potter and the Deathly Hallows”),

new XElement(ns+“Author”,”J.K. Rowling”),

new XElement(ns+“Price”,”14.99),

new XElement(ns+”Available”,”True”)