HNA
HNA

Reputation: 107

Create same LINQ anonymous type from different XML element

I have an XML file like this:- XML file

Notice that each <Field></Field> can have different element like the highlighted <I32> or <String>. I want to show the element name in a datagridview like this which Type is for the name of element (either I32 or String or other child element of <Field>) :- Datagridview

So far, I've tried this code but it return An unhandled exception of type 'System.NullReferenceException'.

XDocument doc = XDocument.Load("GetLotDetails.xml");
var data = doc.Descendants("Document").Where(x => (String)x.Attribute("name") == "DATA").SelectMany(x => x.Elements("Field"));
var query = from d in data
            let str = d.Element("String").Name
            let other = d.Element("I32").Name
            select new
            {
                 Name = d.Attribute("name").Value,
                 Type = str.Equals("String") ? "String" : (other.Equals("I32") ? "I32" : null),        
                 Value = d.Value,
            };
dataGridView1.DataSource = query.ToList();

So the idea is to let the anonymous Type = *whatever element name under field*. How can I extracted different name of element in the LINQ select statement and give it to the same unknown type variable?

Upvotes: 3

Views: 144

Answers (1)

Aluan Haddad
Aluan Haddad

Reputation: 31803

It has nothing to do with anonymous types. You are missing a null check

var query = 
    from d in data
    let element = d.Element("String") ?? d.Element("I32")
    select new
    {
        Name = d.Attribute("name").Value,
        Type = element?.Name,
        d.Value
    };

In your original query, you unconditionally read the Name from both possible nodes, but for any given d, one of the nodes will be null. I could have written it using the null conditional operator, d.Element("String")?.Name, but the above is more readable in this context as the additional projection in your original query adds noise and potential confusion.

Upvotes: 5

Related Questions