Home › Forums › C# Programming › Manipulate XML File Data Using C#
- This topic has 0 replies, 1 voice, and was last updated 19 years, 3 months ago by will.
- AuthorPosts
- August 7, 2005 at 2:10 am #1922willParticipant
Manipulate XML File Data Using C#
By Anand NarayanaswamyNearly 95 percent of .NET applications use XML for various tasks. A main usage for Web developers is combining XML with HTML to display information on Web pages, which relieves them from having to spend a long time editing the content on their Web pages. A single change to an XML file will be reflected across the entire Web site, thus simplifying the development and also greatly reducing the development time.
With the advent of .NET, programming languages such as C#, Visual Basic .NET, and frameworks such as ASP.NET took advantage of XML’s rich features. In fact, the configuration file (web.config), which is used in ASP.NET applications, is completely built upon XML tags.
This article demonstrates how to manipulate an XML file using C#. The manipulation includes displaying, adding, editing, and deleting data from a single XML file using C#. It also shows how to use the Stream class included in the System.IO namespace and various other XML classes included in the System.XML namespace.
Display Contents of XML File
Listing 1 shows a simple XML file for demonstration:
Listing 1123456789101112<?xml version="1.0"?><books><book ID="001"><author>Mark</author><publisher>Sams</publisher></book><book ID="002"><author>Joe</author><publisher>AWL</publisher></book></books>To test the above XML file for errors, simply open it with your browser. If it has no errors, the file will be displayed as such.
The next step is to display all the data using a C# console application (see Listing 2).
Listing 2:12345678910111213141516171819202122232425DisplayCatalog.csXmlNodeList xmlnode = xmldoc.GetElementsByTagName("Book");Console.WriteLine("Here is the list of catalogsnn");for(int i=0;i<xmlnode.Count;i++){XmlAttributeCollection xmlattrc = xmlnode.Attributes;//XML Attribute Name and Value returned//Example: <book id = "001">Console.Write(xmlattrc[0].Name);Console.WriteLine(":t"+xmlattrc[0].Value);//First Child of the XML file - Catalog.xml - returned//Example: <author>Mark</author>Console.Write(xmlnode.FirstChild.Name);Console.WriteLine(":t"+xmlnode.FirstChild.InnerText);//Last Child of the XML file - Catalog.xml - returned//Example: <publisher>Sams</publisher>Console.Write(xmlnode.LastChild.Name);Console.WriteLine(":t"+xmlnode.LastChild.InnerText);Console.WriteLine();</book>Listing 2 is just an extract from the DisplayCatalog() method of the C# application. It displays the data from the XML file. It uses the XMLNodeList class to retrieve the relevant XML node and then iterates it with the help of the for loop and the Count property of the class. Inside the loop, it creates an instance of the XMLAttributeCollection class and displays the appropriate values using the properties of the class.
Inside the constructor, the code creates an instance of the FileStream class and sets the required permissions (see Listing 3). It then loads the XML document with the help of the XMLDocument class and loads the required instance of the FileStream class with the Load() method of the XMLDocument class.
Listing 3:1234DisplayCatalog.csFileStream fs = new FileStream(path,FileMode.Open,FileAccess.Read, FileShare.ReadWrite);xmldoc = new XmlDocument();xmldoc.Load(fs);DisplayCatalog();The above walkthrough showed how to display the contents of an XML file using a C# program. The next section demonstrates how to write data directly to the XML file using a C# console application.
Write Data Directly to XML File
Listing 4 appends a new catalog entry to the XML document using the various properties and methods of the XMLDocument class.
Listing 4:123456789101112131415161718192021222324252627282930313233343536373839404142AddCatalog.cs// New XML Element CreatedXmlElement newcatalogentry = xmldoc.CreateElement("Book");// New Attribute CreatedXmlAttribute newcatalogattr = xmldoc.CreateAttribute("ID");// Value given for the new attributenewcatalogattr.Value = "005";// Attach the attribute to the XML elementnewcatalogentry.SetAttributeNode(newcatalogattr);// First Element - Book - CreatedXmlElement firstelement = xmldoc.CreateElement("Book");// Value given for the first elementfirstelement.InnerText = "Peter";// Append the newly created element as a child elementnewcatalogentry.AppendChild(firstelement);// Second Element - Publisher - CreatedXmlElement secondelement = xmldoc.CreateElement("Publisher");// Value given for the second elementsecondelement.InnerText = "Que Publishing";// Append the newly created element as a child elementnewcatalogentry.AppendChild(secondelement);// New XML element inserted into the documentxmldoc.DocumentElement.InsertAfter(newcatalogentry ,xmldoc.DocumentElement.LastChild);// An instance of FileStream class created// The first parameter is the path to the XML file - Catalog.xmlFileStream fsxml = new FileStream(path,FileMode.Truncate,FileAccess.Write,FileShare.ReadWrite);// XML Document Savedxmldoc.Save(fsxml);
- AuthorPosts
- The forum ‘C# Programming’ is closed to new topics and replies.