0

I have an xml file like this:

  <CommissionTypes>
    <Type>CPA</Type>
    <Lender>
      <Seq>001</Seq>
      <PostUrl>http://www.mysite.com</PostUrl>
    </Lender>
  </CommissionTypes>
</Lenders>

Having got the data like this:

var config = XDocument.Load(xml);

I need to map it to a class collection, the class is structured like this:

public class Lender
{
    public string Type { get; set; }
    public int Seq { get; set; }
    public string PostUrl { get; set; }

    public void Lender(string type, int seq, string postUrl)
    {
        Type = type;
        Seq = seq;
        PostUrl = postUrl;
    }
}

I've been trying to do this for some time using linq, but without success as yet. What i want to do is retrieve all lenders with in the type "CPA" or any other type.

Any advice?

// * UPDATE * //

The update below is where I'm currently at. Its not working, getting a 'object reference not set to an instance' error wgere arrow is.

<CommissionTypes>
  <Type type="CPA">
    <Lender>
      <Seq>001</Seq>
      <PostUrl>http://www.mysite.com</PostUrl>
    </Lender>
  </Type>
</CommissionTypes>

    public static List<Lender> GetLenders(string xml)
    {
        var myXml = XDocument.Load(xml);

        var lenders = new List<Lender>();

        lenders = (from type in myXml.Descendants("Type")
               where type.Attribute("type").Value == "CPA"
        ===>   select new Lender(
                "CPA",
                type.Element("Seq").Value.ConvertTo<int>(),
                type.Element("PostUrl").Value)).ToList();

        return lenders;
    }
dotnetnoob
  • 10,783
  • 20
  • 57
  • 103

1 Answers1

1

Your query is incorrect, because Seq is not a direct child of Lender element.

public static List<Lender> GetLenders(string xml)
{
    var myXml = XDocument.Load(xml);

    var lenders = new List<Lender>();

    lenders = (from type in myXml.Descendants("Type")
               where type.Attribute("type").Value == "CPA"
               from lender in type.Elements("Lender")
               select new Lender(
                    "CPA",
                    (int)lender.Element("Seq"),
                    (string)lender.Element("PostUrl"))).ToList();

    return lenders;
}
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263