Click to See Complete Forum and Search --> : Outputting a single attribute from an XML file


templersstorms
February 26th, 2010, 09:48 PM
When I run the code below, it out puts the "uname" and "type" attribute values for all entries in the XML with type="Troop" to dataGridView1. What I want it to do is to just output the "uname" value and not the "type" value. Any ideas? I have already tried replacing unitType.Add(Unit); with unitType.Add(Unit.uname); but then it just output the length of the name and nothing else. I just started teaching myself C# a few days ago, so I thank you VERY much for any help.

var Units = from Unit in document.Descendants("Unit")

select new
{
type = Unit.Attribute("type").Value,
uname = Unit.Attribute("uname").Value,

};

var filteredUnits = from Unit in Units
where Unit.type == "Troop"
select Unit;



BindingSource unitType = new BindingSource();
foreach (var Unit in filteredUnits)
unitType.Add(Unit);


dataGridView1.DataSource = unitType;

templersstorms
February 26th, 2010, 09:50 PM
Can't figure out how to edit. But I forgot to put in there that I am using Visual Studio C# Express 2008

nelo
March 1st, 2010, 06:50 AM
Your code snippets raises a few questions. I realise you're new so I'll try and be gentle...:). When you post code on the forum you should use code tags. They are easy just put surround the code text with [/ code]. Secondly the 'Edit' button should be available at the bottom right hand corner of the post. Thirdly when posting code you need to provide as much information as possible to make the diagnosis of the problem easier especially if you are new to the technology. In this case it is not clear what 'unitType' actually apart from the fact that its clear that it is some kind of collection. You also don't say anything about the data grid view. Have you defined the columns manually? If you don't want to output the "type" attribute one obvious solution would be to hide that specific column. On the other hand you could change the definition of 'filteredUnits' so it looks like this
[code]
var filteredUnits = from Unit in Units
where Unit.type == "Troop"
select Unit.uname;

Notice I'm just selecting the 'uname' property.

All the best. Chances are you've solved the problem already...put hopefully you can take something from this reply. :)