简体   繁体   中英

How to read Xml File Using LINQ in C#

I'm having an XML file like

<root>
  <Child val1="1" val2="2"/>
  <Child val1="3" val2="4"/>
  <Child val1="5" val2="6"/>
  <Child val1="7" val2="8"/>
  <Child val1="9" val2="10"/>
  <Child val1="11" val2="12"/>
  <Child val1="13" val2="14"/>
</root>

i need to read the attribute values of val1 and val2 to a List<String>

the resulting list will contain

{ "1" , "2" , "3" , ........ ,"13" , "14" }

Here is my sample code:

XDocument XD = XDocument.Load(Application.StartupPath + "\\foo.xml");
List<String> l_lstTemp = XD.Descendants("Child")
                           .Select(X => new List<String> { X.Attribute("val1").Value,
                                                           X.Attribute("val2").Value })
                           .SelectMany(X => X)
                           .Distinct()
                           .ToList();

is there any way to do this using Select instead of selectMany ?

How to modify my existing expression ?

SelectMany is doing exactly what you want here - it's flattening the result from a sequence of lists of strings to a single sequence of strings. Why would you want to take working code which expresses exactly what you need and change it?

Admittedly you can simplify it somewhat by using SelectMany slightly differently, and using an array instead of a list to shorten things a bit too::

XDocument doc = XDocument.Load(Application.StartupPath + "\\foo.xml");
List<String> values = doc.Descendants("Child")
                         .SelectMany(x => new[] { x.Attribute("val1").Value,
                                                  x.Attribute("val2").Value })
                         .Distinct()
                         .ToList();

Your problem scenario is exactly what SelectMany is there for so I think anything we might try to do to eliminate it would just complicate things. :)

The initial .Select is returning a result of IEnumerable's and without the .SelectMany we'd get:

{
 IEnumerable<string> [ "1", "2" ]
 IEnumerable<string> [ "3", "4" ]
 etc...
}

.SelectMany takes an IEnumerable will 'flatten' the initial results into another IEnumerable leaving you with what you want:

{
 IEnumerable<string> [ "1", "2", "3", "4" ]
}

Here is a great post with a much better description A Visual Look at the LINQ SelectMany Operator .

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