1

I'm using Linq to XML to read in an XML file and as part of this I'd like to create an object. My object looks like this:

    public class Address
    {
        public string AccountRef { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        // more stuff here
    }

And my XML file looks like this:

<rows>
    <row>
      <FIELD NAME="AccountRef">1234</FIELD>
      <FIELD NAME="AddressLine1">My Address Line 1</FIELD>
      <FIELD NAME="AddressLine2">My Address Line 2</FIELD>
    </row>
    <row>
      <FIELD NAME="AccountRef">5678</FIELD>
      <FIELD NAME="AddressLine1">My Address Line 3</FIELD>
      <FIELD NAME="AddressLine2">My Address Line 4</FIELD>
    </row>
</rows>

In terms of code, I've tried various things, but at present I have the following which returns the correct number of rows in the format:

<row><FIELD NAME="AccountRef">1234</FIELD><FIELD>...rest of data</row>
<row><FIELD NAME="AccountRef">5678</FIELD><FIELD>...rest of data</row>

The code that does this is:

var results = (from d in document.Descendants("row")
               select d).ToList();

So basically what I'm trying to do is something like:

var results = (from d in document.Descendants("row")
               select new Address
               {
                   AccountRef = d.Attribute("AccountRef").Value,
                   AddressLine1 = d.Attribute("AddressLine1").Value
               }).ToList();

Obviously because my nodes are the same (FIELD NAME) that won't work, so does anyone have an idea how I can achieve this?

1 Answer 1

3

you need to retrive field names and values before creating objects

var results = document.Descendants("row")
    .Select(row=>row.Elements("FIELD").ToDictionary(x=>x.Attribute("NAME").Value, x=>x.Value))
    .Select(d=>new Address 
       {                    
        AccountRef = d["AccountRef"],
        AddressLine1 = d["AddressLine1"],
        AddressLine2 = d["AddressLine2"],
       });

check demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.