Click here to Skip to main content
15,562,015 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi frnds..,

I have an task that the Root node parameter name should bind in an list box
(i.,e)

My xml File

XML
<?xml version="1.0" encoding="UTF-8"?>
-<catalog> -<book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description> An in-depth look at creating applications with XML. </description> </book> -<book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description> A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world. </description> </book>


My Output in listbox should be as
book id
author
title
genre
price
publish_date
description



Is it possible if so pls give me some possible solutions Thank YOu
Posted

Use LINQ to XML
C#
var doc = new XDocument();
doc.Load(something);
List<string> list=new List<string>();
foreach(var name in doc.Root.Element("catalog").DescendantNodes().OfType<XElement>()
        .Select(x => x.Name).Distinct())
{
    list.Add(name);
}

//Bind the list to Listbox


Hope this helps
 
Share this answer
 
v2
Comments
usha C 24-Jul-13 4:02am    
Thanks fr ur code sir am getting dis error...
my error is
"System.Xml.XmlDocument' does not contain a definition for 'Root' and no extension method 'Root' accepting a first argument of type 'System.Xml.XmlDocument' could be found (are you missing a using directive or an assembly reference?)"

I have used my namespaces
using System.Linq;
using System.Xml.Linq;

wat error is iits????
Jameel VM 24-Jul-13 4:27am    
use XDocument instead of XmlDocument
usha C 24-Jul-13 5:00am    
I jus modify ur code sir since i got some error in ur code
After the modification also i faced wit some error...........

XDocument doc = XDocument.Load("Book.xml");

List<string> list = new List<string>();
foreach (var name in doc.Root.Element("catalog").DescendantNodes().OfType<xelement>()
.Select(x => x.Name).Distinct())
{
ListBox1.Items.Add(name.ToString());
}


The error is
"Object reference not set to an instance of an object."
In my for loop
Jameel VM 24-Jul-13 5:03am    
put like this{
list.Add(name);
}
ListBox1.DataSource=list;
Jameel VM 24-Jul-13 5:04am    
Please verify the xml is loaded or not.may be doc is null that's why u got exception
C#
XDocument doc = XDocument.Load("Book.xml"); if (doc != null) { foreach (var name in doc.Root.DescendantNodes().OfType().Select(x => x.Name).Distinct()) { ListBox1.Items.Add(name.ToString()); } }


It gives Exact result....
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900