C# Tutorials and offshore development in India
Tutorials Resources Forum Reviews Communities Interview Jobs Projects Training Your Ad Here


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » C# Syntax »

Parse an XML file and map it with a given TreeView control


Posted Date: 18 Feb 2009    Resource Type: Code Snippets    Category: C# Syntax
Author: MASNSNMember Level: Gold    
Rating: 1 out of 5Points: 9



This class will serve as an XML parser, it parses a given xml file and maps it into an treeview node


public class XmlParser
{
public TreeView treeView;
public string Path { get; set; }
public XmlParser() { }
public XmlParser(string path , TreeView treeView)
{
this.Path = path;
this.treeView = treeView;
StreamReader oReader = new StreamReader(path);
string Content = oReader.ReadToEnd();
XElement xe = XElement.Parse(Content);
int i = 0;
List list = new List();
foreach (XElement el in xe.Elements())
{
list.Add(new TreeNode(el.Name.ToString()));
foreach (XElement subel in el.Elements())
{
list[i].Nodes.Add(new TreeNode(subel.Name.ToString() + " : " + subel.Value));
}
foreach (XAttribute attr in el.Attributes())
{
list[i].Nodes.Add(new TreeNode(attr.Name.ToString() + " : " + attr.Value));
}
i++;
}
treeView.Nodes.AddRange(list.ToArray());
}

}



Responses to the resource: "Parse an XML file and map it with a given TreeView control"
Author: Miss Meetu Choudhary    22 Feb 2009Member Level: Diamond   Points : 1
It would be good if you put the sample of XML file too

Thanks and regards
Meetu Choudhary
Editor


Author: MASNSN    22 Feb 2009Member Level: Gold   Points : 2
Hi there,
Well this code could be applied on any data structured xml file for example







Lybia

1,759,541 km2

6,173,579

Triapolis

Dinar

ly







Tunisia

163,610 km2

10,327,800

Tunis

Dinar

tn







Algeria

2,381,741 km2

33,769,669

Alger

Dinar

dz







Morroco

446,550 km2

31,352,000

Ribat

Dirham

ma







Mauritania

1,030,700 km2

3,069,000

Nouag Chot

Ouguiya

mr





Save this file in C:\NorthAfrica.xml then

Create a new Windows application and add a treeview named treeview1 within the from and size it
Afterward, in the page load event handler add

XmlParser myParser = new XmlParser("C:\NorthAfrica.xml",treeview1);

Finally, run the project





Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Parse XML file map TreeView control  .  XElement  .  AddRange  .  XAttribute  .  TreeNode  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Reading a Textfile and storing in Array,C#
Previous Resource: Age calculation in C#
Return to Discussion Resource Index
Post New Resource
Category: C# Syntax


Post resources and earn money!
 
More Resources




About Us    Contact Us    Privacy Policy    Terms Of Use