Click here to Skip to main content
Licence CPOL
First Posted 14 Jun 2010
Views 18,956
Downloads 576
Bookmarked 15 times

Introduction to XML and XSLT in C#.Net

By | 15 Jun 2010 | Article
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

XML_and_XSLT_Example.jpg

Creating and Reading XML

In this example, I have created 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 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 'System.Xml' namespace.

Using XmlDocument

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 object of XmlDocument

XmlDocument xmldoc = new XmlDocument();

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

xmldoc.RemoveAll();

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

CreateElement is used to create new element in xml file.

For example, I have created root element as follows;

ElmntRoot = xmldoc.CreateElement("Sample"); 

where "Sample" is the element name

If you want to set attribute at the current node then use SetAttribute as follows;

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

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

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

Now let's add child element under root element as follows.

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

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

ElmntRoot.AppendChild(ele1);

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

You can add more child nodes just as mentioned above.

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

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

Create child elements for each listviewitem contents 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 xml file, root element must be declared. All other elements are added under this root element. And all elements should have start tag <Name> and end tag </Name>.
Once you have added all elements and attributes, and appended them to root element, final step is to append this root element to xmldocument as follows.

xmldoc.AppendChild(ElmntRoot);

And then save xml file to specified location.

xmldoc.Save(sfd.FileName);


Using XmlTextWriter

//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 object of XmlTextWriter, giving xml file fullpath, and encoding technique.

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

Code to create xml using XmlTextWriter is different from XmlDocument.

Here first open xml document to write using code

textWriter.WriteStartDocument();

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

textWriter.WriteComment("Your comments.");

To create root element, use

textWriter.WriteStartElement("Sample");

You can add attributes to element using

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

Child elements can be added as follows

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

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

textWriter.WriteEndElement();

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

Then create full end tag using

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 xml document and close it.

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

This is all about creating xml in C# using XmlDocument and XmlTextWriter.

I will discuss reading and modifying existing xml file and transforming it to HTML using XSLT in next article. But you can find C# code for the same in project attached.

License

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

About the Author

Pallavi Wasnik

Software Developer

India India

Member

Follow on Twitter Follow on Twitter
Bachelore of Engineering in Electronics and Communication. Currently working as a Executive Software Developer. Working on technologies like C#.Net, XML, HTML, XSL, ASP.Net, SQL from last 3 yrs.
 
She likes dancing, sketching, making friends. She loves to learn different things, it can be anything (technologies, languages, arts, many more...).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionThank you but waiting for rest..!! Pinmembersushree_pattnaik1:23 2 Apr '12  
GeneralNice one Pinmembernkumar4you3:40 12 Oct '10  
GeneralRe: Nice one PinmemberPallavi Wasnik22:47 26 Oct '10  
GeneralMy vote of 5 PingroupTHE SK1:47 30 Aug '10  
GeneralRe: My vote of 5 PinmemberPallavi Wasnik22:45 26 Oct '10  
GeneralGraph in XSLT PinmemberAhmed.lpo23:31 15 Jun '10  
GeneralRe: Graph in XSLT PinmemberPallavi Wasnik0:02 16 Jun '10  
GeneralRe: Graph in XSLT Pinmemberrajnish2patel7:57 3 Aug '11  
GeneralBroken Link Pinmembermomift20:16 14 Jun '10  
GeneralRe: Broken Link PinmemberPallavi Wasnik20:33 14 Jun '10  
GeneralMy vote of 2 PinassociateColin Eberhardt4:39 14 Jun '10  
GeneralRe: My vote of 2 PinmemberPallavi Wasnik19:08 14 Jun '10  
GeneralRe: My vote of 2 PinassociateColin Eberhardt21:31 14 Jun '10  
GeneralRe: My vote of 2 PinmemberPallavi Wasnik19:41 15 Jun '10  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 15 Jun 2010
Article Copyright 2010 by Pallavi Wasnik
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid