In this post we will be reading a simple xml file if you don't know what xml is then here are some links that might help:
- http://www.w3schools.com/xml/xml_whatis.asp
- http://en.wikipedia.org/wiki/XML
- http://www.exforsys.com/tutorials/xml/xml-advantages.html
so for this post i preferred not to go for a window based app but for a console based app since i just wanted to display the data from the xml file into the console, so here's how it goes:
launch Visual studio and create a console based application with the base language as c sharp give your project an appropriate name and then create the new project
and here's the image of the xml file that we will be parsing
The next step is to create a class and add a function in which we will be writing the logic to parse the xml file, but before writing the logic inside the function we must import a namespace called as:
using System.Xml;
using System.Xml;
this namespace is used to handle the xml file like one can read the xml file and the attributes that it contains or one can create a new xml file at runtime with the help of the classes inside this namespace.
The below code shows you how to read the entire structure of the XML file and display it onto the console
void parseXML(String xmlFileLocation)
{
XmlTextReader reader = new XmlTextReader(xmlFileLocation);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
Console.Write("<" + reader.Name + ">");
break;
case XmlNodeType.Text:
Console.Write("<" + reader.Value + ">");
break;
case XmlNodeType.EndElement:
Console.Write("<" + reader.Name + ">");
break;
}
}
}
Code Explanation: XMLTextReader is a class present in the System.XML namespace used to parse XML files by just taking the URL of your XML file. In the switch case block what i am doing is am just checking what element it is and what value it possesses and display the data on the console with the help of the enumerator XMLNodeType. Here's the view at the final output
Now if you want just the data from the xml file then in that case just modify the above code to
void parseXML(String xmlFileLocation)
{
XmlTextReader reader = new XmlTextReader(xmlFileLocation);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Text:
Console.WriteLine( reader.Value);
break;
}
}
Here's the output snap
void parseXML(String xmlFileLocation)
{
XmlTextReader reader = new XmlTextReader(xmlFileLocation);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Text:
Console.WriteLine( reader.Value);
break;
}
}
Here's the output snap
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6o1ryuc-8NapAnyhnr9S5LxpmgNQqmz9FjJtLZPm7sI6Iftr2Fkq2Xi9vtg7X8cvIWVPsLUDHPHrG7kLfOvxEOnk2dcozxjaNWNxwbrlIghYcAJnbR6JiOKHnDQRZJAcBgmwImlq6q3yQ/s400/Consoleop2.png)
I hope that this post has helped you in understanding the concept on how to parse the XML file and getting out its data.
No comments:
Post a Comment