Your supposition is correct; as @maccettura explained, that's how Dictionary
works.
This said, remeber that <SaleGroupsFiles>
should have a matching tag for your XML to be valid.
As per your question, this is a possible idea:
var results =
root
.Descendants("SaleGroup")
.ToDictionary(element => element.Attribute("id").Value.ToString(), element => element.ToString());
I.e. adding as keys the value of the id
attribute of your elements, supposing they're unique.
Actually this question
What is the proper way to read the data?
is hard to answer to, since... it depends on what you want to do with the data.
Do you want to create SaleGroup
objects? In that case, rather than creating a dictionary, you can just create a List<SaleGroup>
, if you provide a SaleGroup
class.
Another option would be deserializing your XML.
Also, keep in mind that element.Name will give the element's name (e.g. SaleGroup), while maybe you want to read the value of the name
attribute (e.g. "Canada")?
EDIT
Since you are ok with a slightly more realistic solution, if you declare these classes
public class SaleGroup
{
public int Id { get; set; }
public bool Active { get; set; }
public string Name { get; set; }
public SaleFile File { get; set; }
}
public class SaleFile
{
public string Location { get; set; }
public string FileType { get; set; }
public string Destination { get; set; }
}
you can edit your code this way:
var results =
root
.Descendants("SaleGroup")
.Select(element => new SaleGroup()
{
Active = Convert.ToBoolean(element.Attribute("active").Value),
Id = Convert.ToInt32(element.Attribute("id").Value),
Name = element.Attribute("name").Value,
File = new SaleFile()
{
Destination = element.Descendants("files").Single().Attribute("destination").Value,
FileType = element.Descendants("files").Single().Attribute("fileType").Value,
Location = element.Descendants("files").Single().Attribute("location").Value
}
})
.ToList();
It is also possible to optimize the code above, e.g. to read element.Descendants("files").Single()
just once, or modify it to allow more than one SaleFile
inside your SaleGroup
class.