I was wondering if there is a way to get a list of results into a list with linq to xml. If I would have the following xml for example:
<?xml version="1.0"?>
<Sports xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SportPages>
<SportPage type="test">
<LinkPage>
<IDList>
<string>1</string>
<string>2</string>
</IDList>
</LinkPage>
</SportPage>
</SportPages>
</Sports>
How could I get a list of strings from the IDList?
I'm fairly new to linq to xml so I just tried some stuff out, I'm currently at this point:
var IDs = from sportpage in xDoc.Descendants("SportPages").Descendants("SportPage")
where sportpage.Attribute("type").Value == "Karate"
select new
{
ID = sportpage.Element("LinkPage").Element("IDList").Elements("string")
};
But the var is to chaotic to read decently. Isn't there a way I could just get a list of strings from this?
Thanks
This query works - tested and verified:
var ID2 = (from sportpage in xDoc.Descendants("SportPages").Descendants("SportPage")
where sportpage.Attribute("type").Value == "Karate"
select sportpage)
.Descendants("LinkPage")
.Descendants("IDList")
.Elements("string")
.Select(d => d.Value)
.ToList();
Gives me a list of two strings, "1" and "2".
var myStrings = xDoc.Descendants("SportPage")
.Where(d => d.Attribute("type").Value == "Karate")
.Descendants("IDList")
.Descendants("string")
.Select(d => d.Value);
to see your string:
xDoc.Descendants("SportPage")
.Descendants("IDList")
.Where(d => d.Attribute("type").Value == "Karate")
.Descendants("string")
.Select(d => d.Value)
.ToList()
.ForEach(Console.WriteLine);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With