C# XML Read and Write

    1 Votes


The XML is the Extensible Markup Language. It is basically designed to improve the functionality of the web by providing flexibility and adaptable information identification. It is a language for structured documentation. The XML is called extensible because it is in a not fixed format like HTML. XML is a `metalanguage' a language which describes other language and let us designs our own customized markup languages for different types of documents.

Why use XML?
We use XML because it removes two constraints of the web development:
  • Dependence on a single.
  • Inflexible document type (HTML).

It allows the flexibility to develop the user defined document types. It also provides a robust, non-proprietary and verifiable file for storage and transmission of text and data both on and off the web and it removes the complexity options of SGML, by making it easier.

Uses of XML:
  • It defines standards for data transfer across applications.
  • Good for describing structured data.
  • Easy to do Type matching.
  • Easy to write.
  • Validation through DTD.
  • More input constraints.
Advantages:
  • Enables smarter searching than full text searches. 
  • Enables smart data extraction.
  • Enables business to business communication no matter which systems each use.
  • Flexible, universal. 
  • Standardization for syntax.
  • Platform independent.

 

How can XML be used?
  • It separates data from html.
  • It is used to exchange the data.
  • It is used to share the data.
  • It is used to store the data.
  • Data is available to more users not only to browsers.

Let us have a look at a sample XML document:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE bookdetail SYSTEM "a.dtd">
<bookdetails>
<bookinfo>
<title> C </title>
<author>
<fauthor> Herbert </fauthor>
<lauthor>Scvhildt </lauthor>
</author>
<qty>1234</qty>
<price>123</price>
</bookinfo>
<bookinfo>
<title> Java</title>
<author>
<fauthor> Herbert </fauthor>
<lauthor>Scvhildt </lauthor>
</author>
<qty>12344</qty>
<price>1234</price>
</bookinfo>
</bookdetails>

Sample C# Program to read from XML

For a given XML below, we will write a program to read each and every node of the XML and print thier values.

<?xml version="1.0" encoding="utf-8"?>
<Books>
  <book>
    <title>C++</title>
    <author>Balaguruswamy</author>
  </book>
  <book>
    <title>C#</title>
    <author>O Reily</price>
  </book>
  <book>
    <title>Java</title>
    <price>Herbert Schildvt</price>
  </book>
</Books>

So the given code is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (XmlReader reader= XmlReader.Create(@"c:\users\gr33n synt4x\documents\visualstudio2010\Projects\ConsoleApplication1\ConsoleApplication1\myData.xml"))
            {
                while (reader.Read())
                {
                    if (reader.IsStartElement())
                    {
                        switch (reader.title.ToString())
                        {
                            case "title":
                                Console.WriteLine("Title of the book is : " + reader.ReadString());
                                break;
 
                            case "author":
                                Console.WriteLine("Author is : " + reader.ReadString());
                                break;
                        }
                    }
                    Console.WriteLine("");
                }
            }
            Console.ReadKey();
        }
    }
}

Output:

Title of the book is: C++
Author is: Balaguruswamy
Title of the book is: C#
Author is: O Reily
Title of the book is: Java
Author is: Herbert Schildvt
Writing in XML file:
using System;
using System.Text;
using System.Xml;

Sample C# Program to create an XML Document

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlWriter write = XmlWriter.Create ("books.xml");
            write.WriteStartDocument ();
            write.WriteStartElement ("Books");
            write.WriteStartElement ("book");
            write.WriteAttributeString ("title");
            write.WriteString ("C#");
            write.WriteEndElement ();
            write.WriteStartElement ("book");
            write.WriteAttributeString ("title");
            write.WriteString ("C++");
            write.WriteEndDocument ();
            write.Close ();
        }
    }
}

Output:

<Books>
<book title>C# </book>
<book title>C++ </book>
</Books>

Direct Attributes Access

Following sample C# Program will help us to read a node in XML directly.

using System;
using System.IO;
using System.Xml;
public class Sample {
  public static void Main() {
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("" +
                "C#" +
                "350" +
                "");
    XmlNode node = doc.FirstChild;
    //Display the contents of the child nodes.
    if (node.HasChildNodes)
    {
      for (int i=0; i<node.ChildNodes.Count; i++)
      {
        Console.WriteLine(node.ChildNodes[i].InnerText);
      }
    }
  }
}

Output:
C#
350

SGML

The SGML is a Standard Generalized Markup Language; it is an international standard for defining the descriptions of structure of different types of electronic document. It is very large, powerful and complex. The XML is a lightweight cut down version of SGML and has functionality to make it useful but has removes all the optional features which make SGML too complex to program in a web environment.

The XML has made easy and straightforward to use SGML on the Web. It is easy to author, manage SGML defined documents, define document types, and easy to transmit and share them across the Web.

HTML v/s XML

XMLHTML
It is case sensitive. It is not case sensitive.
It is used to describe data. It is used to define data.
Ending tags can never be omitted in XML. Ending tags can be omitted.
Data interchange is possible. Data interchange is not possible.
The documents are reusable and extensible in XML. The documents are not reusable and extensible in HTML.