简体   繁体   中英

How to get multiple elements by name in XML using LINQ

I've the below XML:

<?xml version="1.0" standalone="yes"?>
<TestSuite>
  <TestCase Name="XXX" ID="123;234; 345; 456">
    <CodeBlock />
  </TestCase>
  <TestCase Name="East" ID="11,22,33, 44, 55">
    <CodeBlock />
  </TestCase>
</TestSuite>         

I need to get all the ID and order them by ID ASC, below is my Linq:

var r = (from lv1 in xdoc.Descendants("TestCase")
         select new { ID = lv1.Attribute("ID").Value })
        .Where(d => d.ID != string.Empty)
        .GroupBy(l => l.ID)
        .ToList();

I now get:

123;234; 345; 456
11,22,33, 44, 55

But how can I get the IDs like:

11
22
33
44
55
123
234
345
456

It's not clear why you're grouping at all... and you just need to split the values and flatten that with SelectMany , by the looks of it:

var separators = new[] { ';', ',' };
var r = xdoc.Descendants("TestCase")
            .Select(x => (string) x.Attribute("ID"))
            .Where(ids => ids != null)
            .SelectMany(ids => ids.Split(separators,
                                         StringSplitOptions.RemoveEmptyEntries))
            .Select(id => int.Parse(id.Trim()))
            .OrderBy(id => id)
            .ToList();

Note that I've parsed each ID as integer, on the grounds that if you treat them just as strings, then "123" comes before "55". If they're actually not necessarily integers, but you want to sort any values which can be parsed as integers that way, then the ordering part becomes trickier.

This might work:

var r = (from lv1 in xdoc.Descendants("TestCase")
        select new { ID = lv1.Attribute("ID").Value }).
        Where(d => d.ID != string.Empty).OrderBy(l => int.Parse(l.ID)).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM