How to create xml document in C#

How to create xml document in C#

Creating an xml document in c# is an easy task. In this page, we will explain you how to create an xml document as given below:

<?xml version="1.0" encoding="UTF-8"?>
<body>
  <level1>
    <level2>text</level2>
    <level2>other text</level2>
  </level1>
</body>

We will provide two different methods that can be used to create XML files in C# programming language.

• XMLDocument based approach

• LINQ based approach

Using XmlDocument to create XML files in C#

Required using statements:

using System;
using System.Xml;
using System.Xml.XmlDocument

 Example code to create XML document using XmlDocument and XmlElement classes:

XmlDocument doc = new XmlDocument( );

//(1) the xml declaration is recommended, but not mandatory
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
XmlElement root = doc.DocumentElement;
doc.InsertBefore( xmlDeclaration, root );

//(2) string.Empty makes cleaner code
XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
doc.AppendChild( element1 );

XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
element1.AppendChild( element2 );

XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
XmlText text1 = doc.CreateTextNode( "text" );
element3.AppendChild( text1 );
element2.AppendChild( element3 );

XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
XmlText text2 = doc.CreateTextNode( "other text" );
element4.AppendChild( text2 );
element2.AppendChild( element4 );

doc.Save( "D:\\xml-document.xml" );

Using LINQ to XML to create XML documents in C#

Required using statements:

using System;
using System.Xml.Linq;

Example code to create XML document using XDocument and XElement classes:

XDocument doc = new XDocument(
    new XElement( "body",
    new XElement( "level1",
    new XElement( "level2", "text" ),
    new XElement( "level2", "other text" )
)));
doc.Save( "D:\\xml-document.xml" );


How to create xml document in C#
added 5 years 11 months ago

- C# Parse Tree
- How to create xml document in C#
- C# ØMQ Server Client Example, C# ZeroMQ Sender Receiver Pair
- C/C++ ØMQ Server Client Example, ZeroMQ Sender Receiver Pair