Reputation: 23
I am trying to get the relevant data from my xml file. So for example I wish to select all of the data from the element called Roker Park, from the venue element. How do I only select that data and not the rest of it? This is my xdocument
<Funrun>
<Venue>
<Name>Roker Park</Name>
<Runner>
<Charity>Cancer Research</Charity>
<Firstname>Roger</Firstname>
<Lastname>Malibu</Lastname>
<Sponsorship>550</Sponsorship>
</Runner>
<Runner>
<Charity>Arthritis UK</Charity>
<Firstname>Adam</Firstname>
<Lastname>White</Lastname>
<Sponsorship>340</Sponsorship>
</Runner>
<Venue>
<Name>Victoria Park</Name>
<Runner>
<Charity>Against Malaria Foundation</Charity>
<Firstname>Rob</Firstname>
<Lastname>Tate</Lastname>
<Sponsorship>850</Sponsorship>
</Runner>
<Runner>
<Charity>Fred Follows Foundation</Charity>
<Firstname>Peter</Firstname>
<Lastname>Jackson</Lastname>
<Sponsorship>500</Sponsorship>
</Runner>
</Venue>
</Funrun>
The code I've got so far selects all of venues data so I get Victoria Parks as well as Rokers, this is the code I've got so far:
List<string> VenueNames = new List<string>();
List<string> VenueDataList = new List<string>();
var doc = XDocument.Load("XMLFile1.xml");
var doc2 = XDocument.Load("XMLFile2.xml");
var doc3 = XDocument.Load("XMLFile3.xml");
var combinedunique = doc.Descendants("Venue")
.Union(doc2.Descendants("Venue"))
.Union(doc3.Descendants("Venue"));
foreach (XElement element in combinedunique.DescendantsAndSelf("Venue"))
{
VenueNames.Add(element.Element("Name").Value.ToString());
}
if (Convert.ToString(lstboxVenues.SelectedItem) == VenueNames.ElementAt(0))
{
foreach (XElement element in combinedunique.DescendantsAndSelf("Firstname"))
{
VenueDataList.Add(element.Value);
}
for (int i = 0; i < VenueDataList.Count; i++)
{
lstboxVenueData.Items.Add(VenueDataList.ElementAt(i));
}
}
Upvotes: 2
Views: 695
Reputation: 236188
Getting all venue names:
List<strgin> VenueNames = combindedunique.Select(v => (string)v.Element("Name")).ToList();
Output:
[
"Roker Park",
"Victoria Park"
]
Getting first names by given venue name:
string venueName = "Victoria Park"; // name you want to search by
List<string> VenueDataList =
combindedunique.Where(v => (string)v.Element("Name") == venueName)
.Elements("Runner")
.Select(r => (string)r.Element("Firstname"))
.ToList();
Output:
[
"Rob",
"Peter"
]
Upvotes: 2