AuthorsDen.com   Join | Login    
Where Authors and Readers come together!

SIGNED BOOKS    AUTHORS    BOOKS    SAMPLE CHAPTERS    AUDIOBOOKS    eBOOKS    STORIES    ARTICLES    POETRY    BLOGS    NEWS    VIDEOS    SUCCESS    TESTIMONIALS

Featured Authors:  Judith Bailey, iJames Hill, iSergio Serrano, Ph.D., iKarin Adams, iPaul Lonardo, iH.G. Potter, iLinda Frank, iBrendan O'Brien, iJohn DeDakis, iEdward Patterson, i

  Home > Technology > Articles Popular: Books, Stories, Articles, Poetry      Authors: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z     

Anand Narayanaswamy

 Follow Me  

· Contact Me
· Books
· Articles
· News
· 2 Titles
· 5 Reviews
· Save to My Library
· Share with Friends!
·
Member Since: Mar, 2007

Anand Narayanaswamy, click here to update your pages on AuthorsDen.


Working with XML using C#
by Anand Narayanaswamy   
Rated "G" by the Author.
     

eXtensible Markup Language (XML) is one of the powerful language for representing data over the web. It is easy to understand and is also platform independent. Nearly 95% of .NET applications make use of XML for performing various tasks.

The language can be easily combined with HTML for displaying information on a webpage. With XML, developers need not have to spend long time for editing the content on their web pages. A single change to an XML file will be reflected across the whole of the web site thus simplifying the development and also greatly reduces the developer’s time.

In this article, you will learn how to manipulate an XML file using C# programming language. Manipulation includes displaying, adding, editing and deleting data from a single XML file using C#. You will also learn how to make use of Stream class included with System.IO namespace and various other XML classes included with System.XML namespace. For the purpose of this article, I have created an XML file as shown in listing 1.1.

Listing 1.1





Mark
Sams



Joe
AWL




You should test the above XML file for any errors by simply opening the file using your browser. If there are no errors then the XML file will be displayed as such.

We will display all the data from the above XML file using a C# console application (See Listing 1.2)

XmlNodeList xmlnode = xmldoc.GetElementsByTagName("Book");
Console.WriteLine("Here is the list of catalogs\n\n");

for(int i=0;i {
XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;

//XML Attribute Name and Value returned
//Example:

Console.Write(xmlattrc[0].Name);
Console.WriteLine(":\t"+xmlattrc[0].Value);

//First Child of the XML file - Catalog.xml - returned
//Example: Mark

Console.Write(xmlnode[i].FirstChild.Name);
Console.WriteLine(":\t"+xmlnode[i].FirstChild.InnerText);

//Last Child of the XML file - Catalog.xml - returned
//Example: Sams

Console.Write(xmlnode[i].LastChild.Name);
Console.WriteLine(":\t"+xmlnode[i].LastChild.InnerText);
Console.WriteLine();

The above listing is just an extract from the C# program. The code pulls the data from our XML file. It makes use of XMLNodeList class to retrieve the relevant XML node and then iterates it with the help of for loop and the class Count property. Inside the loop an instance of XMLAttributeCollection class is created and the appropriate values are displayed using the properties of the class.

Inside the constructor an instance of FileStream class is created (See Listing 1.3) and the required permissions are set. The XML document is loaded with the help of XMLDocument class and the required instance of FileStream class is loaded with Load() method of XMLDocument class. DisplayCatalog() method is the one which we discussed in listing 1.2

Listing 1.3

FileStream fs = new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
xmldoc = new XmlDocument();
xmldoc.Load(fs);
DisplayCatalog();

You can download complete source code for all the examples covered on this article from the code download section at the end of this article.

The final output looks like as shown in figure 1.1






Adding Data to an XML file using C# application

The code given below appends a new catalog entry to the XML document. It uses the various properties and methods of the XMLDocument class. Initially, a new XML element and attribute are created. The attribute is then attached to the XML element with the help of SetAttributeNode method. We then create the first and second elements and the require values are supplied by using the InnerText property. The newly created elements are appended to the XML file by using AppendChild method. After the above mentioned process, the new XML element is inserted into the file with the help of appropriate methods.


// New XML Element Created
XmlElement newcatalogentry = xmldoc.CreateElement("Book");

// New Attribute Created
XmlAttribute newcatalogattr = xmldoc.CreateAttribute("ID");

// Value given for the new attribute
newcatalogattr.Value = "005";

// Attach the attribute to the xml element
newcatalogentry.SetAttributeNode(newcatalogattr);

// First Element - Book - Created
XmlElement firstelement = xmldoc.CreateElement("Book");

// Value given for the first element
firstelement.InnerText = "Peter";

// Append the newly created element as a child element
newcatalogentry.AppendChild(firstelement);


// Second Element - Publisher - Created
XmlElement secondelement = xmldoc.CreateElement("Publisher");

// Value given for the second element
secondelement.InnerText = "Que Publishing";

// Append the newly created element as a child element
newcatalogentry.AppendChild(secondelement);

// New XML element inserted into the document
xmldoc.DocumentElement.InsertAfter(newcatalogentry,xmldoc.DocumentElement.LastChild);

// An instance of FileStream class created
// First parameter is the path to our XML file - Catalog.xml

FileStream fsxml = new FileStream(path,FileMode.Truncate,FileAccess.Write,FileShare.ReadWrite);

// XML Document Saved
xmldoc.Save(fsxml);

As you can see from the above code, the new child node gets inserted after the last child node. It can be added before the last child node using InsertBefore method of XMLDocument class. Finally, an instance of FileStream class is created and the document is saved using Save() method of XMLDocument class.


Want to review or comment on this article?


Need a FREE Reader Membership?
Reviewed by Mary Coe
Reviewed on June 25, 2007
You are so knowledgeable. You look so young. Great article. Very interesting read.

Reviewed by Sandie May Joyce
Reviewed on May 22, 2007
You are so knowldgeable!

Sandie Angel :o)

Reviewed by m j hollingshead
Reviewed on March 19, 2007
interesting article

Popular Technology Articles
  1.  Heroes of VW Beetledom: Bela Barenyi
  2.  Thermodynamic augmentation of engine c
  3.  Mid-engine or rear-engine? Porsche's q
  4.  Welcome to Californication, suckers!
  5.  Free the Net!
  6.  Hey Cortana...(2019)
  7.  1984
  8.  CHALLENGER: A disaster destined to hap
  9.  Feeling QWERTY?
  10.  Obscene Gasoline
  11.  The Schismatic Nature of Contemporary
  12.  Time Waster
  13.  Is 'Intelligent Life' an evolutionary
  14.  A Place in the Sun
  15.  CAR 'STUFF'
  16.  The BLIMP
  17.  Manufacturing Jobs
  18.  Space Shuttle Blog
  19.  The Good, Bad & Ugly of the Brave New
  20.  Intelligence and the Machine
  21.  and in this corner the Macintosh.
  22.  Delegate or Stagnate
  23.  Needed: A Worldwide Network to Defeat
  24.  NASA at 60
  25.  American Innovation

Free Book Review Program
Select a book to read and review today!

Growing up Automotive by CHARLES ROSE

Having spent the majority of his life immersed in the automotive world, Charlie Rose shares his most memorable moments.  
Member BookAds

Forced Hot Air Furnace - Troubleshooting and Repair by Roger Vizi

Complete Troubleshooting & Repairing guide to hot air furnaces * Complete operation, maintenance, and repair * Covers gas, oil, and electric forced air systems * Includes flowcharts and highlighted tips and solutions to common furnace problems  
Member BookAds

The Computer Part e- v4 by RickthePoetWarrior

Get your AI (art-is-visual intelligence) reprogrammed as this aulde technology reveals nu_technology's secrets  
Member BookAds