Reader Level:
ARTICLE

Processing XML Data: Part 1

Posted by Sudhakar Chaudhary Articles | XML October 29, 2012
In this article I will show you how to work with XML Data.
  • 0
  • 0
  • 6632
Download Files:
 

In this article I will show you how to work with XML Data.

XML data can be processed in a .NET application using the System.Xml namespace. The System.xml namespace contains many classes by which we can be create, process and validate XML documents.

Writing XML Data

The XmlWriter class in the System.Xml namespace provides non-cached, forward-only, and write-only access to XML Data. This class can be used to write either a stream of data or text data.

XmlWriter objects are created using the Create () method. The Create () method is a static method.

For writing XML Data you can use the XmlWriterSettings class. You can pass the object of the XmlWriterSettings class into the Create () Method to specify the setting or properties, which you want to enable on the XmlWriter object.

NOTE: if an XmlWriterSettings is not passed as a parameter, the default settings are applied. Some of The properties of the XmlWriterSettings class are given below.

XmlWriterSettings

Description

Default Value

CheckCharacters

Get or Set a value indicating whether to do character checking or not

true

ConformanceLevel

Get or Set the level of compliance with which the System.Xml.XmlWriter Compiles with.

false

Encoding

Get or Set the text encoding to use.

Encoding.UTF8

Indent

Get or Set a value indicating whether to indent elements or not.

false

IndentChars

Get or Set the character string to use while indenting.

Tow Spaces

NewLineOnAttributes

Get or Set a value indicating whether to write attributes on the new line or not.

false

OmitXmlDeclaration

Get or Set a value indicating whether to write an XML declaration or not.

false

Example of the XmlWriterSettings and XmlWriter class:

Example-of-the-XmlWriterSettings-and-XmlWriter-class.jpg

An XML File includes elements, attributes, and comments. All these can be created using various methods of the XmlWriter class.

Creating Elements in an XML File

There are two ways for creating Elements.

  1. Using WriteElementString() Method

    This method takes two parameters, the name of the element and the value of the element.

    //writer is an object of the XmlWrither class
    writer.WriteElementString("Name"," sharpcorner");
     
  2. Using WriteStartElement() Method

    This method takes the name of an element as a parameter. After calling this method, you need to call the WriteString() method to specify a value for the element. Finally, you need to call the WriteEndElement() method to end the element tag.
    //writer is an object of the XmlWrither class
    writer.WriteStartElement("Name");
    writer.WriteString("sharpcorner ");
    writer.WriteEndElement();

Note

You can also store the value of variables as an element value in an XML File. For this you need to convert the value of the variable into a string type. You can do this by using XmlConvert class.

double Salary = 25000.00;
//writer is an object of the XmlWriter class
           
writer.WriteElementString("Salar",XmlConvert.ToString(Salary));

Creating Attributes in an XML File

You can create attributes in an XML File in two ways:

  1. Using WriteAttributeString() Method

    This method takes two parameters, the name of the attribute and the value of the attribute.
    //writer is an object of the XmlWrither class
    writer.WriteAttributeString("User_ID"," 0001");
     
  2. Using WriteStartAttribute()Method

    This method takes the name of the attribute as a parameter. After calling this method you need to call the WriteString() method to write the value of the attribute. Finally you need to call the WriteEndAttribute() method to end the attribute tag.
    //writer is an object of the XmlWriter class
    writer.WriteStartAttribute("User_ID");
    writer.WriteString("0001");
    writer.WriteEndAttribute();

Writhing Comment in an XML File

You can write comments in an XML file by using the WriteComment() method. This method takes a string as a parameter.

//writer is an object of the XmlWriter class
writer.WriteComment("This XML File Stores the Details of Users.");

Creating an XML File

An XML file can be created in following ways:

  • By using XmlWriter
  • By using XmlTextWriter
  • By saving a DataSet as XML data

Creating an XML File using XmlWriter

Here is an example of XmlWriter:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Xml;

 

namespace xml_2

{

    class Program

    {

        static void Main(string[] args)

        {

            XmlWriterSettings setting = new XmlWriterSettings();

            setting.Indent = true;

            setting.IndentChars = "  ";

            setting.NewLineOnAttributes = true;

 

            //Create XML File

            using (XmlWriter writer =   XmlWriter.Create("C:\\OrderDetails.xml", setting))

            {

                //Write Comment

                writer.WriteComment("Order Detils of Company.");

                //Create the root element

                writer.WriteStartElement("OrderDetails");

                //Create an element called Order

                writer.WriteStartElement("Order");

                //Create attribute of the Order element

                writer.WriteAttributeString("OrderID", "0001");

                //Create tow elements ProductName and Price with the values Toys and 100

                writer.WriteElementString("ProductName", "Toys");

                writer.WriteElementString("Price", "100");

                //Close the Order element

                writer.WriteEndElement();

                //Create another Order element

                writer.WriteStartElement("Order");

                writer.WriteAttributeString("OrderID","0002");

                writer.WriteElementString("ProductName","Sationary");

                writer.WriteElementString("Price","30");

                writer.WriteEndElement();

                //Close the root element

                writer.WriteEndElement();

                //Flush the buffer to the underlying stream

                writer.Flush();

            }

        }

 

    }

}

Output

Creating-an-XML-File-using-XmlWriter.jpg



Creating an XML File Using XmlTextWriter

The XmlTextWriter class implements the XmlWrite class. You can create a XML file using the XmlTextWriter class as well. The method of the XmlTextWriter class is given below.
 

Methods

Description

WriteStartDocument()

Writes the following XML declaration in the beginning of an XML document : <?xml version="1.0"?>

WriteStartElement()

The start tag for a specified element.

WriteElementString()

Element that contains a string value.

WriteStartAttribute()

Start of attributes.

WriteAttributeString()

The value of given attributes.

WriteEndAttribute()

The end of attributes.

WriteEndElement()

End tag of element.

WriteEndDocument()

End The Document


Here is an example of
XmlTextWriter:
 

using (XmlTextWriter writer = new XmlTextWriter("C:\\Users.xml", null))

            {

                //open the doument

                writer.WriteStartDocument();

                //write comments

                writer.WriteComment("Users.xml file created using XmlTextWriter");

                //write the root element

                writer.WriteStartElement("UsersDetails");

                //write the next element

                writer.WriteStartElement("User");

                writer.WriteAttributeString("UserID", "U0001");

                writer.WriteElementString("Name", "Sam Flin");

                writer.WriteElementString("Email", "sam.flin@gmail.com");

                writer.WriteElementString("Age", "20");

                writer.WriteEndElement();

                //end the doument

                writer.WriteEndDocument();

                writer.Close();

 

            } 

Output

XML-File-Using-XmlTextWriter.jpg

Saving Dataset as XML Data

The GetXml() method returns the XML representation of a dataset. The dataset object also contains a certain method that enables you to write XML Data.
 

Methods

Description

WriteXml()

Write the data of the dataset into an XML File.

WriteXmlSchema()

Write the data of the dataset as an XML Schema


//create dataset

 DataSet ds = new DataSet();

 //create datatable

 DataTable dt = new DataTable("UserDetails");

 dt.Columns.Add("Name");

 dt.Columns.Add("Address");

 dt.Columns.Add("Email");

 ds.Tables.Add(dt);

 DataRow dr = dt.NewRow();

 dr["Name"] = "Jhon Carter";

 dr["Address"] = "102/1 Block- C Marvlin";

 dr["Email"] = "jhon.carter@corner.com";

 dt.Rows.Add(dr);

 dr = dt.NewRow();

 dr["Name"] = "Shara Corner";

 dr["Address"] = "102/2B Block- D NewLand";

 dr["Email"] = "shara.corner@gmail.com";

 dt.Rows.Add(dr);

OUTPUT

Use the WriteXml method on a dataset and write the output is as:

//write UserDetails Table contents to XML file
ds.WriteXml("C:\\User.xml");

The WriteXml method takes the destination of the XML output as a parameter. It is also takes an optional XmlWriteMode option parameter that specifies how the XML ouput is be written.

Saving-Dataset-as-XML-Data.jpg

OUTPUT

Use the GetXml() method on a dataset and write the output is as:

//ds is object of dataset
string xmlString = ds.GetXml();
Console.WriteLine(xmlString);

output.jpg

OUTPUT

Use the WriteXmlSchema() method on a dataset and write the output is as:

//write xml schema
ds.WriteXmlSchema("C:\\UserSchema.xml");

output1.jpg

COMMENT USING

Trending up