Can someone explain the LINQ to XML below? Also, what is the correct way to check if the method returned a List with Data? Do you just check if the List is empty.
Code:
public List<Listing> GetList() { if (File.Exists(this.xmlFilePath)) { XDocument doc = XDocument.Load(this.xmlFilePath); var listings = from row in doc.Root.Elements('listing') select new Listing { A = (string)row.Element('A'), B = (string)row.Element('B'), C = (string)row.Element('C'), D = (string)row.Element('D'), E = (string)row.Element('E') }; return listings.ToList(); } else { return new List<Listing>(); } }
XML:
<Listings> <listing> <a>A</a> <b>B</b> <c>C</c> <d>D</d> <e>E</e> </listing> <listing> <a>F</a> <b>G</b> <c>C</c> <d>H</d> <e>I</e> </listing> </Listings>
You can check if
listingshas any data by examining the result of theCount()method on thelistingsvariable, and to answer the question asked in the comments section below, ‘So, there is no way to actually returnnull? I have to return aList<listing>()object?’, please see the following code:I think that’s what you’re after.
There isn’t much to explain about how the code works. In the first part of the query:
The expression
doc.Root.Elements('listing')selects all of the<listing>elements below the document root (<Listings>).The second part of the query creates a new
Listingobject for each<listing>element and assigns the inner text of each of theA,B,C,DandEchild elements to each of theA,B,C,DandEproperties of each newListingobject created.The line containing:
return listings.ToList();returns a genericList<T>ofListingobjects.Using the sample XML provided, you’ll find that each
Listingobject’sA,B,C,D,andEproperties will benull. This is because the character case of each of therow.Element()selectors is different from the XML being queried, i.e. your XML has<a>androw.Element('A')uses an uppercase'A'. XML node matching in LINQ to XML is case-sensitive.