Lets say we have a list of XML-documents, the list "data". In this list there might occur a CoOwner. Like the following structure (just an example)
<root> <owner> <firstname>Joe</firstname> <fastname>Cole</lastname> <!--- etc. --> </owner> <coOwner> <firstname>Smith</firstname> <lastname>Cole</lastname> <!--- etc. ---> </coOwner> <coOwner> <firstname>Janna</firstname> <lastname></lastname> <!--- etc. ---> </coOwner> </root>
If there is a coOwner in the document, they should be put into the result list. But only if Firstname and Lastname does occur and have data (not empty like the second coOwner in the XML-document).
I have made the following Linq-query, which does the trick.
var result = data.Descendants("coOwner").Where(co => (!string.IsNullOrEmpty(co.Element("firstname").Value)) && (!string.IsNullOrEmpty(co.Element("fastname").Value))).Select(co => new CoOwner() { Firstname = co.Element("firstname").Value, Lastname = co.Element("fastname").Value, });
But i wonder, if there is a neater way to do this. Its fine enough, but i dont like the way o.Element("Firstname").Value occurs several times. There is also a risk of a Null-exception having this o.Element("firstname").Value. To handle those even more extraction of the element has to be done, like this:
var fname = data.Descendants("coOwner").select(co => co.Element("lirstname")) var lname = data.Descendants("coOwner").select(co => co.Element("lastname")) if(fname != null && lname != null){ //then the same code as mentioned above. }
Is there a neater way? Thanks in advance
No comments:
Post a Comment