Sunday, July 18, 2010

XML in Dotnet

This article covers:


1. Basic concepts of XML.

2. Example of adding an XML file in Visual Studio.

3. Different ways of Processing XML

a. XMLReader and XMLWriter

b. XmlDocument

c. XPath.

4. Loading XML data into Dataset.



Basic contepts of XML:

What is XML: XML is a standard by W3C.

XML provides structure to the ordinary text data.

It is used for exchanging information between objects developed in different programming languages. It is used to exchange data between incompatible systems over internet.

Data is stored in plain text format in xml file.

What is a well formed xml document ?

Ans: Every XMLdocument must be well formed

1. It should have only one root element tag.

2. Tags are case-sensitive and hence the opening and closing tag case must match.

3. Every tag must be closed.

4. Tags must not overlap each other.

5. The value of attributes must be enclosed in quotes.

What is XML Schema document?

Ans: It contains declarations of various XML constructs including elements, attributes etc. These declarations define the syntax and the restrictions while using them in an XML document. An XML document is validated using XML schema document and it is optional.





2. Example of adding XML file in a Website.

1. Open Microsoft Visual Studio2008. Go to File ->New ->Website -> Select ASP.NET website under Visual Studio Installed Templates ->Browse for the location where you want to create your website or type the folder name as XMLDemo.

2. Go To View in the MenuBar and select Solution Explorer. Right Click on your Web Application and select Add New Item-> Select XML File under Visual Studio Installed Templates. Give the name for the XMl file as Employee.xml. This will Add Employee.xml file in your application.

3. Open the Employee.xml file (It will be opened as soon as you add it to your application). The instruction below

<?xml version="1.0" encoding="utf-8" ?> implies that this is an xml file version 1.0 and the encoding format is utf-8.

4.Type the below text into the XML file.

<EmployeeInfo>


<Employee id="1">


<Name>xyz</Name>


<Department>IT</Department>


</Employee>


<Employee id="2">


<Name>abc</Name>


<Department>Sales</Department>


</Employee>


<Employee id="3">


<Name>bbb</Name>


<Department>HR</Department>


</Employee>


<Employee id="4">


<Name>aaa</Name>


<Department>IT</Department>


</Employee>


<Employee id="5">


<Name>ccc</Name>


<Department>HR</Department>


</Employee>


</EmployeeInfo>




Loading XML data from an XML document into Dataset

DataSet ds = new DataSet();//Create a new Dataset


ds.ReadXml(MapPath("Employee.xml"));//Read the xml file contents into dataset


StringBuilder sb = new StringBuilder();//using stringbuilder object to display xml file contents from dataset


//displaying the contents of the Table "Employee"


foreach (DataRow dr in ds.Tables["Employee"].Rows)


{


foreach (DataColumn dc in ds.Tables["Employee"].Columns)


{


sb.Append( dr[dc.ColumnName] + " "); //separate each column value separated with space.


}


sb.Append("<br/>");//Go to next line


}


Response.Write(sb);//display the data




write an XML representation of a DataSet to a string .

Below example shows how to obtain the XML representation of the DataSet as a string. We use the GetXml method as shown in the following example.

//Getting xml data from the dataset


string xmlData = ds.GetXml();


Response.Write(xmlData);






//Writing data from the dataset to Employee1.xml file without the schema


ds.WriteXml(MapPath("Employee2.xml"), XmlWriteMode.IgnoreSchema);






///Writing data from the dataset to Employee1.xml file along with the schema


ds.WriteXml(MapPath("Employee1.xml"), XmlWriteMode.WriteSchema );



The XML classes in the System.Xml namespace allow you to work with XML documents and data.

The XML classes support parsing and writing XML, editing XML data in memory, data validation and XSLT transformation.

In the .Net Framework, we have following XML namespaces:

System.Xml, System.Xml.XPath, System.Xml.Xsl, System.Xml.Schema, System.Xml.Linq.

Different ways of XML Processing :

1. Stream based XML processing: The XmlReader and XmlWriter classes provide a non-cached, forward-only means of processing XML data.

2. In-Memory XML processing: XmlDocument class and XPathNavigator class.

Stream based XML Processing :

1. XmlReader provides forward-only, read-only access to a stream of XML data. It is an abstract class.

2. XMLTextReader and XMLTextWriter are stream based parsers:

• XMLTextReader represents a reader that provides fast, non-cached, forward-only access to xml data.

• Used if the XML document needs to be parsed only once.

• Parsing the XML document using stream based parsers is faster when compared to DOM API as the complete document is not loaded into memory at once.

• XMLTextReader is only used for READONLY operations.

• XMLTextWriter can be used only to create a new XML file, but we cannot modify the already existing XML file.

3. Using XMLTextReader to read all the employee id’s from the Employee.xml file

Steps:

a. Initialize a new instance of XmlTextReader class with the specified file Employee.xml.

b. Position the reader for reading from the XML file using Read() method.

c. Check if the NodeType is XmlNodeType.Element and the node name is “Employee”.

d. Get the attribute value from the node and display it.

e. Close the XML Reader.

XmlTextReader xr = new XmlTextReader(MapPath("Employee.xml"));


while (xr.Read())//Reader is advanced using the Read method.


{


//Gets the id of each employee by comparing the nodetype with element and name with "Employee"


//Then retreives the attribute of that element.


if (xr.NodeType == XmlNodeType.Element && xr.Name == "Employee")


{


string attributeValue = xr.GetAttribute("id");


Response.Write(attributeValue + " ");


}


}


xr.Close();//Close the XmlTextReader


4. Read and Display the names of the Employee


//Display the names of the Employee.


XmlTextReader xr = new XmlTextReader(MapPath("Employee.xml"));


while (xr.Read())//Reader is advanced using the Read method.


{






if (xr.NodeType == XmlNodeType.Element && xr.Name == "Name")


{


//First way of reading the data


xr.Read(); //Reads the text node.


Response.Write(xr.ReadContentAsString());






Response.Write("<br/>");//Go to next line






//Second way of reading the data


// Response.Write(xr.ReadString() + " ");






}


}


Xr.Close();

No comments:

Post a Comment