Working with XML in .Net


In this we see what is XML. how is it different from HTML. Also we see an example of how to use it in windows application for writing and reading an XML file.

Extensible Markup Language (XML) is a tag based meta language which is used to describe the data in hierarical manner.
It allows userdefined tags that make XML document handling more flexible than the conventional language
of the Internet, i.e. HTML.It is the core representation of of data in .net

What Is the objective of XML?

The major objective is to organize data in such a way so that it can be read easily by everyone; in addition, the document itself is technology and platform independent.

Consider the following Example:

ID1 Subhash .Net 45,000
ID2 Pulak Java 40,000
It is diffcult to understand exactly what information the above file contains.


Now if we define it in XML document format.

I have attached the code in XML format as it cant be displayed over here. Kindly see the attchment.



XML document is quiet different from a standard HTML document with additional user-given tag names.E.g. In HTML document if we spell tags incorrectly
the browser will just ignore it.it means HTML is case insensitive but Xml is case sensitive.

Basic Rules for creating XML document:

1. Each Xml document have a root element. Not more than one root element is created.
2. Each element must have a start-tag and end-tag.
3. In XML one single element contain all other element sinside it.
4. Cese Sensitive language so tags should be defined properly.
5. The first letter of an attribute's name must begin with a letter or with an underscore.

In our above example employees is the root element. Employee is the element inside which other elemets are written.


Now consider an example in which we have to enter the details of employee and save it as XML document. For this we take a windows application and on the design page add some textboxes labels and buttons. I have attached the design page see it for reference.

we have three buttons one for writing xml, One for reading and the third for appending it.

On write button click we write the following code:

 FileStream fs = new FileStream("z:\\Employee.xml", FileMode.OpenOrCreate, FileAccess.Write);
XmlTextWriter writer = new XmlTextWriter(fs, null);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("Employees");
writer.WriteStartElement("Employee");
writer.WriteAttributeString("id", textBox_eid.Text.ToString());
writer.WriteElementString("name", textBox_ename.Text);
writer.WriteElementString("dept", textBox_edept.Text.ToString());
writer.WriteStartElement("birthdate");
writer.WriteElementString("day", textBox_date.Text.ToString());
writer.WriteElementString("month", textBox_month.Text.ToString());
writer.WriteElementString("year", textBox_year.Text.ToString());
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
fs.Close();
MessageBox.Show("XML file created");


I this code we first create a XML file using for writing the data from textbox. If file already exist then it gets opened for writing inside it.

WriteStartdocument writes the upper most line i.e. the declaration of XML where XML version is mentioned.
WriteStartElement Write a tag with the given local name.
WriteAttributeStringWrite attribute with the specified local name and value.
And at last each start element is closed using "WriteEndElement".

Here i have given the path Z:\\Employee.xml. you can use your own path.

Now, On the Read button code is for reading the the Xml document and show it in textbox. Code is like this:


FileStream fs = new FileStream("z:\\Employee.xml", FileMode.Open, FileAccess.Read);
XmlTextReader reader = new XmlTextReader(fs);
reader.WhitespaceHandling = WhitespaceHandling.None;
int tb = textBox_ename.TabIndex;
do
{
while (reader.Read())
{

switch (reader.NodeType)
{
case XmlNodeType.Element:
//Console.WriteLine(reader.Name + ":-");
if (reader.HasAttributes)
{

Console.WriteLine("Attributes of <" + reader.Name + ">");
while (reader.MoveToNextAttribute())
{
textBox_eid.Text = reader.Value;
}
// Move the reader back to the element node.
reader.MoveToElement();
}
break;
case XmlNodeType.Text:

if (tb == 1)
{
textBox_ename.Text = reader.Value;
}
else if (tb == 2)
{
textBox_edept.Text = reader.Value;
}
else if (tb == 3)
{
textBox_date.Text = reader.Value;
}
else if (tb == 4)
{
textBox_month.Text = reader.Value;
}
else if (tb == 5)
{
textBox_year.Text = reader.Value;
}
tb++;
break;


}
if (tb==6)
{
break;
}
}
} while (tb==5);
reader.Close();
fs.Close();


We will first read the data using xmlReader and store it in reader than we create a loop which executes until the reader has some value inside it.
we will check whether hte data is an attribute, element or text and work accordingly. If it is text we will check for the tabindex and accordingly enter the
data in the textbox according to the tabindex.
whiteSpaceHanding gets or sets a value that specifies how whitespace is handled.

At the last append button which will edit the data and save it in the same document. Note that changes is not sone in the data we created earlier
another node is developed which contains edited data.


XmlDocument doc = new XmlDocument();
doc.Load("z:\\Employee.xml");
XmlNode root = doc.DocumentElement;
XmlElement emp = doc.CreateElement("Employee");
emp.SetAttribute("id", textBox_eid.Text.ToString());
emp.InnerXml = "" + textBox_ename.Text + "" + textBox_edept.Text
+ "
" + textBox_date.Text.ToString() + ""
+ textBox_month.Text.ToString() + "
" + textBox_year.Text.ToString() + "
";

root.AppendChild(emp);

XmlWriter writer = new XmlTextWriter("z:\\Employee.xml", null);
doc.WriteTo(writer);
MessageBox.Show("file append");
writer.Close();


It will append the data and create a new node and save the data from textbox to these nodes.


Attachments

  • "Xml format to write code" (42242-222057-xml-format.txt)
  • Comments

    No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: