Click here to Skip to main content
15,881,248 members
Articles / Programming Languages / XSLT

Introduction to XML and XSLT in C# .NET

Rate me:
Please Sign up or sign in to vote.
3.95/5 (13 votes)
19 Nov 2013CPOL5 min read 164.9K   4.8K   43   23
In this article, you will see how to create and read the XML file, how to add new elements, new attributes and replace the value of existing element in/from existing XML file.

Introduction

When I started working on XML for my project, I was very new to the concept. Of course there are a lot of resources you can find on internet regarding how to read and write XML file in .NET, how to transform it in HTML file, how to change the existing XML file. But I didn't find a single resource that covers all these topics.

In this example I have included all these topics like creating XML file, reading XML file, adding elements and attributes to existing XML file, transforming XML to HTML passing attributes from .cs file to .xsl file.

Using the code

XmlXslExample/XML_and_XSLT_Example.jpg

Creating and Reading XML

In this example, I have created an XML file using two techniques.

  • Using XmlDocument
  • Using XmlTextWriter

Fill the fields Name, Age, Job, Education, click 'Create XML using XmlDocument' or 'create XML using XmlTextWriter' button, XML file (sampleXML.xml) will create.

sampleXML.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<!--Your comments.-->
<Sample name="pal">
   <Name>pal</Name>
   <Age>24</Age>
   <Job>software</Job>
   <Education>
         <Exam>BE</Exam>
         <Discipline>ETC</Discipline>
         <College>XYZ</College>
         <Percent>62%</Percent>
   </Education>
   <Education>
          <Exam>12</Exam>
         <Discipline>ET</Discipline>
         <College>ABC</College>
         <Percent>87%</Percent>
   </Education>
</Sample>

Let's discuss the code now. To work with XML, first you need to add the System.Xml namespace.

Using XmlDocument

C#
XmlDocument xmldoc = new XmlDocument();
XmlElement ElmntRoot;
//Create XML using XmlDocument 
private void createXML()
{
   xmldoc.RemoveAll();
   xmldoc.AppendChild(xmldoc.CreateProcessingInstruction("xml", "version='1.0'"));

   SaveFileDialog sfd = new SaveFileDialog();
   sfd.FileName = Application.StartupPath + "\\sampleXML.xml";

   ElmntRoot = xmldoc.CreateElement("Sample");
   //Adding attribute
   ElmntRoot.SetAttribute("name", textBox1.Text);
   //Adding text to element
   XmlElement ele1 = null;
   ele1 = xmldoc.CreateElement("Name");
   ele1.InnerText = textBox1.Text;
   ElmntRoot.AppendChild(ele1);

   XmlElement ele2 = null;
   ele2 = xmldoc.CreateElement("Age");
   ele2.InnerText = textBox2.Text;
   ElmntRoot.AppendChild(ele2);

   XmlElement ele3 = null;
   ele3 = xmldoc.CreateElement("Job");
   ele3.InnerText = textBox3.Text;
   ElmntRoot.AppendChild(ele3);

   foreach (ListViewItem item in listView1.Items)
   {
         XmlElement ele4 = null;
         ele4 = xmldoc.CreateElement("Education");
         XmlElement child1 = null;
         child1 = xmldoc.CreateElement("Exam");
         child1.InnerText = item.SubItems[0].Text;
         ele4.AppendChild(child1);
         XmlElement child2 = null;
         child2 = xmldoc.CreateElement("Discipline");
         child2.InnerText = item.SubItems[1].Text;
         ele4.AppendChild(child2);
          XmlElement child3 = null;
          child3 = xmldoc.CreateElement("College");
         child3.InnerText = item.SubItems[2].Text;
         ele4.AppendChild(child3);
          XmlElement child4 = null;
         child4 = xmldoc.CreateElement("Percent");
         child4.InnerText = item.SubItems[3].Text;
         ele4.AppendChild(child4);
         ElmntRoot.AppendChild(ele4);
   }
   xmldoc.AppendChild(ElmntRoot);
   xmldoc.Save(sfd.FileName);
   MessageBox.Show("XML file created.", 
     "Sample", MessageBoxButtons.OK, MessageBoxIcon.Information);
   System.Diagnostics.Process.Start(sfd.FileName);
}

To create XML using XmlDocument, first declare an object of XmlDocument.

C#
XmlDocument xmldoc = new XmlDocument();

Then remove all nodes and attributes (if they already exists).

C#
xmldoc.RemoveAll();

Declare the root element, XmlElement ElmntRoot; The root element is the parent element for all other elements.

CreateElement is used to create a new element in the XML file.

For example, I have created the root element as follows;

C#
ElmntRoot = xmldoc.CreateElement("Sample"); 

where "Sample" is the element name.

If you want to set attributes at the current node then use SetAttribute as follows:

C#
ElmntRoot.SetAttribute("name", textBox1.Text);

In this, name is the name of the attribute and textBox1.Text is the value of the attribute.

An element can have other elements and elements can have attributes too.

Now let's add a child element under the root element as follows:

C#
XmlElement ele1 = null;
ele1 = xmldoc.CreateElement("Name");
ele1.InnerText = textBox1.Text;
ElmntRoot.AppendChild(ele1);

InnerText is used to set the current element value. Once the child element and its value are declared, append the child element to the root element as follows;

C#
ElmntRoot.AppendChild(ele1);

AppendChild is used to add a specified node to the end of the list of child nodes, of this node.

You can add more child nodes just as mentioned above.

To make the XML a little more complex, see the code for adding listview data in XML.

In this code, I have added listviewitem contents under <Education></Education> tags.

Create child elements for each listviewitem content as shown in the code.

In this case <Education> will act as a parent element to its child elements <Exam>, <Discipline>, <College>, <Percent>. These child elements are appended to its parent element <Education>.This parent element finally is appended to root element.

Remember in an XML file, the root element must be declared. All other elements are added under this root element. And all elements should have a start tag <Name> and end tag </Name>. Once you have added all elements and attributes, and appended them to the root element, the final step is to append this root element to xmldocument as follows:

C#
xmldoc.AppendChild(ElmntRoot);

And then save the XML file to the specified location.

C#
xmldoc.Save(sfd.FileName);

Using XmlTextWriter

C#
//Create XML using XmlTextWriter
private void Createxml1()
{
   SaveFileDialog sfd = new SaveFileDialog();
   sfd.FileName = Application.StartupPath + "\\sampleXML.xml";
   XmlTextWriter textWriter = new XmlTextWriter(sfd.FileName, Encoding.UTF8);

   //Create a xml file
   try
   {
         textWriter.Formatting = Formatting.Indented;
         //Open the xml document to write
         textWriter.WriteStartDocument();
         //write commnets
         textWriter.WriteComment("Your comments.");
         //write element
         textWriter.WriteStartElement("Sample");
         //write attribute
         textWriter.WriteAttributeString("name", textBox1.Text);
         textWriter.WriteElementString("Name", textBox1.Text);
         textWriter.WriteElementString("Age", textBox2.Text);
         textWriter.WriteElementString("Job", textBox3.Text);

         foreach (ListViewItem item in listView1.Items)
         {
               textWriter.WriteStartElement("Education");
               textWriter.WriteElementString("Exam", item.SubItems[0].Text);
               textWriter.WriteElementString("Discipline",item.SubItems[1].Text);
               textWriter.WriteElementString("College", item.SubItems[2].Text);
               textWriter.WriteElementString("Percent", item.SubItems[3].Text);
               textWriter.WriteEndElement();
         }
         textWriter.WriteFullEndElement();
         MessageBox.Show("XML file created.", 
           "Sample", MessageBoxButtons.OK, MessageBoxIcon.Information);
         System.Diagnostics.Process.Start(sfd.FileName);
   }
   catch (Exception ex)
   {
         MessageBox.Show(ex.Message);
   }
   finally
   {
         textWriter.WriteEndDocument();
         textWriter.Flush();
         textWriter.Close();
   }
}

Declare an object of XmlTextWriter, giving XML file fullpath, and encoding technique.

C#
XmlTextWriter textWriter = new XmlTextWriter(sfd.FileName, Encoding.UTF8);

Code to create XML using XmlTextWriter is different from XmlDocument.

Here first open the XML document to write using code:

C#
textWriter.WriteStartDocument();

If you want to add comments in your XML, then use

C#
textWriter.WriteComment("Your comments.");

To create root element, use:

C#
textWriter.WriteStartElement("Sample");

You can add attributes to element using:

C#
textWriter.WriteAttributeString("name", textBox1.Text);

Child elements can be added as follows

C#
textWriter.WriteElementString("Name", textBox1.Text);

For each WriteStartElement, there must be its closing property WriteEndElement() as follows;

C#
textWriter.WriteEndElement();

Please note that WriteStartElement and WriteEndElement must be in proper sequence to avoid further errors.

Then create full end tag using

C#
textWriter.WriteFullEndElement();

This is used in case when we have xml tag like <Name />, It does not have a full end element. WriteFullEndElement() will convert this to something like this, <Name></Name> so that end tag will work properly.

Finally end the XML document and close it.

C#
textWriter.WriteEndDocument();
textWriter.Flush();
textWriter.Close(); 

This is all about creating xml in C# using XmlDocument and XmlTextWriter. You can find the code for editing/replacing any element or attribute, adding new element in an existing xml in the attached sample application.

Now lets see how to translate XML into HTML using XSL stylesheet.

XML to HTML using XSLT

I am assuming you have basic knowledge on XSL stylesheet. If not, then I will suggest you to get a basic knowledge on creating XSL file. In attached sample application, you can find sample-stylesheet.xsl in Debug folder.

XSLT is XSL Transformation. This is used to convert any XML document into another type of documents which is recognized by browser (HTML).

Now lets go into the coding part. Following is a code to convert XML file into HTML.

C#
string xmlfile = Application.StartupPath + "\\sampleXML.xml";
//Sending data from cs to XSL 
string logo = Application.StartupPath + "//" + "1rightarrow-32.png";
string name = textBox1.Text;
XsltArgumentList xslArgs = new XsltArgumentList();
xslArgs.AddParam("logo", "", logo);
xslArgs.AddParam("name", "", name); 

XslTransform xslt = new XslTransform();
xslt.Load("sample-stylesheet.xsl");
XPathDocument xpath = new XPathDocument(xmlfile);
XmlTextWriter xwriter = new XmlTextWriter(xmlfile + ".html", Encoding.UTF8);
xslt.Transform(xpath, xslArgs, xwriter, null);
xwriter.Close();

Create object of XSLT .

C#
XslTransform xslt = new XslTransform();

or

C#
XslCompiledTransform xslt = new XslCompiledTransform(); 

Load your stylesheet in this object

C#
xslt.Load("sample-stylesheet.xsl"); 
Load your XML file using XPathDocument:
C#
XPathDocument xpath = new XPathDocument(xmlfile); 
You can pass parameter to your stylesheet from our code using XsltArgument.
C#
XsltArgumentList xslArgs = new XsltArgumentList();
xslArgs.AddParam("logo", "", logo);
xslArgs.AddParam("name", "", name);  
In the stylesheet, parameters are defined as follows
XML
<xsl:param name="logo"/>
<xsl:param name="name"/> 
In the above xslArgs.AddParam code, first parameter "logo" is a name of param you have defined in stylesheet and third parameter "logo" is a value you want to pass to your stylesheet. In sample application attached, I am passing an Image file and a String to a stylesheet which will be shown in our HTML file. Note: XsltArgumentList is optional. If you don't want to pass any arguments, then just write NULL in place of xslArgs in following code. Finally pass these arguments to our object.
C#
xslt.Transform(xpath, xslArgs, xwriter, null);
xwriter.Close();  
Done !!! :) You can convert XML into DOC file too using same above xslt code. Just change ".html" to ".doc" in XmlTextWriter object. Try it yourself. If you have any queries and suggestions, let me know. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Working as a Software Developer for last 8 yrs. Working on technologies like C#.Net, XML, HTML, XSL, WPF .

Comments and Discussions

 
Questionhi Pin
Yogesh Sarangpure4-May-15 21:19
Yogesh Sarangpure4-May-15 21:19 
QuestionNeed More examples about XSLT Pin
santosh panchal6-Jul-14 5:25
santosh panchal6-Jul-14 5:25 
GeneralMy vote of 3 Pin
Vasistan Shakkaravarthi15-May-14 0:23
Vasistan Shakkaravarthi15-May-14 0:23 
GeneralMy vote of 3 Pin
dxs75319-Nov-13 2:16
dxs75319-Nov-13 2:16 
GeneralRe: My vote of 3 Pin
Pallavi Wasnik19-Nov-13 5:21
Pallavi Wasnik19-Nov-13 5:21 
GeneralMy vote of 3 Pin
vsrkraju4-Nov-13 19:17
vsrkraju4-Nov-13 19:17 
Questionwaiting for rest of xsl expalanation Pin
vsrkraju4-Nov-13 19:17
vsrkraju4-Nov-13 19:17 
AnswerRe: waiting for rest of xsl expalanation Pin
Pallavi Wasnik19-Nov-13 5:22
Pallavi Wasnik19-Nov-13 5:22 
GeneralRe: waiting for rest of xsl expalanation Pin
kori1236-Aug-15 10:27
kori1236-Aug-15 10:27 
QuestionThank you but waiting for rest..!! Pin
sushree_pattnaik2-Apr-12 1:23
sushree_pattnaik2-Apr-12 1:23 
GeneralNice one Pin
nkumar4you12-Oct-10 3:40
nkumar4you12-Oct-10 3:40 
GeneralRe: Nice one Pin
Pallavi Wasnik26-Oct-10 22:47
Pallavi Wasnik26-Oct-10 22:47 
GeneralMy vote of 5 Pin
THE SK30-Aug-10 1:47
THE SK30-Aug-10 1:47 
GeneralRe: My vote of 5 Pin
Pallavi Wasnik26-Oct-10 22:45
Pallavi Wasnik26-Oct-10 22:45 
GeneralGraph in XSLT Pin
Ahmed.lpo15-Jun-10 23:31
Ahmed.lpo15-Jun-10 23:31 
GeneralRe: Graph in XSLT Pin
Pallavi Wasnik16-Jun-10 0:02
Pallavi Wasnik16-Jun-10 0:02 
GeneralRe: Graph in XSLT Pin
rajnish2patel3-Aug-11 7:57
rajnish2patel3-Aug-11 7:57 
GeneralBroken Link Pin
momift14-Jun-10 20:16
momift14-Jun-10 20:16 
GeneralRe: Broken Link Pin
Pallavi Wasnik14-Jun-10 20:33
Pallavi Wasnik14-Jun-10 20:33 
GeneralMy vote of 2 Pin
Colin Eberhardt14-Jun-10 4:39
Colin Eberhardt14-Jun-10 4:39 
GeneralRe: My vote of 2 Pin
Pallavi Wasnik14-Jun-10 19:08
Pallavi Wasnik14-Jun-10 19:08 
GeneralRe: My vote of 2 Pin
Colin Eberhardt14-Jun-10 21:31
Colin Eberhardt14-Jun-10 21:31 
GeneralRe: My vote of 2 Pin
Pallavi Wasnik15-Jun-10 19:41
Pallavi Wasnik15-Jun-10 19:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.