Search Forum
(57285 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


              
Printable Version

Creating a XML document with C#
By Pavel Tskekov

Just try this short piece of code, to make an XML document on the fly. In C# working with XML through the System.XML is very easy.

using System;
using System.Xml;

namespace PavelTsekov
{
 class MainClass
 {
  XmlDocument xmldoc;
  XmlNode xmlnode;
  XmlElement xmlelem;
  XmlElement xmlelem2;
  XmlText xmltext;
  static void Main(string[] args)
  {
   MainClass app=new MainClass();
  }
  public MainClass() //constructor
  {
   xmldoc=new XmlDocument();
   //let's add the XML declaration section
   xmlnode=xmldoc.CreateNode(XmlNodeType.XmlDeclaration,"","");
   xmldoc.AppendChild(xmlnode);
   //let's add the root element
   xmlelem=xmldoc.CreateElement("","ROOT","");
   xmltext=xmldoc.CreateTextNode("This is the text of the root element");
   xmlelem.AppendChild(xmltext);
   xmldoc.AppendChild(xmlelem);
   //let's add another element (child of the root)
   xmlelem2=xmldoc.CreateElement("","SampleElement","");
   xmltext=xmldoc.CreateTextNode("The text of the sample element");
   xmlelem2.AppendChild(xmltext);
   xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2);
   //let's try to save the XML document in a file: C:\pavel.xml
   try
   {
    xmldoc.Save("c:\pavel.xml"); //I've chosen the c:\ for the resulting file pavel.xml
   }
   catch (Exception e)
   {
    Console.WriteLine(e.Message);
   }
   Console.ReadLine();
  }
 }
}