Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# linq to xml to list

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

like image 212
WtFudgE Avatar asked Jan 23 '23 07:01

WtFudgE


2 Answers

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".

like image 117
marc_s Avatar answered Jan 26 '23 00:01

marc_s


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);
like image 29
Yuriy Faktorovich Avatar answered Jan 26 '23 00:01

Yuriy Faktorovich