How to use XMLTextWriter with XML Namespaces in C#

You can use the XMLTextWriter class to create XML content that uses a namespace. The code lies used to illustrate the idea are taken from the article How to use XMLTextWriter to create an XML document in C#, and you can find more information about XML namespaces from the article How to use XML Namespaces in XML document.

The XmlTextWriter includes an overloaded version of the WriteStartElement() method that accepts a namespace URI. Here’s how it works:

 

string ns = “http://www.Books.com/BooksList”;

w.WriteStartDocument();

w.WriteStartElement(“BooksList”, ns);

// Write the first book.

w.WriteStartElement(“Book” , ns);