xElement Linq Creating List

Sangram Nandkhile picture Sangram Nandkhile · Dec 30, 2011 · Viewed 9.2k times · Source

I have created new class to read the data from xml file, which looks like :

public class Validations
{
  public string id { get; set; }
  public List<string> lhsList { get; set; }
  public List<string> rhsList { get; set; }
}

XML I am trying to read is:

<root>
<Validation id="val3">
    <lhs id='Estimated' />
    <lhs id='Newqurter' />
    <rhs id='Current' />
    <rhs id='FirstQuarter' />
</Validation>
.
.
.

</root>

Code I have written to read the xml is :

List<Validations> vList = new List<Validations>();
vList = (from XElement xele in xdoc.Root.Elements()
  select new Validations
  { 
    id = xele.Attribute("id").Value.ToString(),
    // lhsList = ((xele.Elements().FirstOrDefault(p => p.Name == "lhs").FirstAttribute.Value
    // rhsList = ((xele.Elements().FirstOrDefault(p => p.Name == "rhs").FirstAttribute.Value
  }
).ToList<Validations>();

How do read the List<lhsList> ? I tried

lhsList = ((xele.Elements().FirstOrDefault(p => p.Name == "lhs").FirstAttribute.Value).ToList(), 

But its not working as expected. What can be other ways to do this?

Answer

ColinE picture ColinE · Dec 30, 2011

You can create the list of lhs elements as follows:

List<string> lhsElements = xele.Elements("lhs")
                               .Select(el => el.Attribute("id").Value)
                               .ToList();

This selects all the lhs elements that are children of xele, then selects the value of their 'id' attribute. I'll leave it to you to work out how to merge this with your code.