XML and CSharp (C#)

Example 1

This Visual Studio Console Application example called xeml.net will explain how to work with XML and C#.

Class Program.cs:

using System;
using System.Collections.Generic;
using System.Text;

namespace xeml.net
{
    class Program
    {
        static void Main(string[] args)
        {
            CSharpXML csxml = new CSharpXML();
        }
    }
}

Class CSharpXML.cs:

using System;
using System.Xml;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace xeml.net
{
    class CSharpXML
    {
        // my fields
        XmlDocument xmldoc;
        XmlNode xmlnode;
        XmlElement xmlelem;
        XmlElement xmlelem2;
        XmlText xmltext;

        public CSharpXML() {

            // Creating a new XmlDocument-object
            xmldoc = new XmlDocument();

            // Create a new node with the XML Declaration
            xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,"","");

            // Add (append) the declaration to the Xml Document
            xmldoc.AppendChild(xmlnode);

            // Create a new node (the root element)
            xmlelem = xmldoc.CreateElement("root");

            // Add text to the root node
            xmltext = xmldoc.CreateTextNode("Hi, i'm the root!");

            // Add (append) the node text to the root element
            xmlelem.AppendChild(xmltext);

            // Add the root element to the document
            xmldoc.AppendChild(xmlelem);

            // Create a new element
            xmlelem2 = xmldoc.CreateElement("childElement");

            // Add text to the childElement
            xmltext = xmldoc.CreateTextNode("i'm the little child");

            // Add (append) the node text to the childElement
            xmlelem2.AppendChild(xmltext);

            // Select the place where you want to add the childElement
            xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2);

            // Try to save the XML document in a file on C:\myDocument.xml or show an error
            try
            {
                xmldoc.Save("c:\\myDocument.xml");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            // Wait for input before closing the Console Application window
            Console.ReadLine();
        }
    }
}

The result must be something like this:

<?xml version="1.0"?>
<root>Hi, i'm the root!<childElement>i'm the little child</childElement></root>