Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xElement Linq Creating List

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?

like image 949
Sangram Nandkhile Avatar asked Dec 30 '11 07:12

Sangram Nandkhile


1 Answers

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.

like image 110
ColinE Avatar answered Nov 04 '22 23:11

ColinE