I have the following code to get some data about companies:
XDocument doc = XDocument.Load(new StringReader(searchPayload));
XNamespace ns = ConfigurationManager.AppSettings["WebServiceNamespace"];
var businesses = (from node in doc.Descendants(ns + "searchResultsRecord")
let ABN = node.Element(ns + "ABN")
let mainName = node.Element(ns + "mainName")
let legalName = node.Element(ns + "legalName")
let mainTradingName = node.Element(ns + "mainTradingName")
let otherTradingName = node.Element(ns + "otherTradingName")
let mainBusinessPhysicalAddress = node.Element(ns + "mainBusinessPhysicalAddress")
select new
{
Name = new
{
organisationName = (string)mainTradingName.Element(ns + "organisationName"),
score = (string)mainTradingName.Element(ns + "score"),
isCurrentIndicator = (string)mainTradingName.Element(ns + "isCurrentIndicator"),
},
ABN = new
{
identifierValue = (string)ABN.Element(ns + "identifierValue"),
identifierStatus = (string)ABN.Element(ns + "identifierStatus"),
},
Location = new
{
stateCode = (string)mainBusinessPhysicalAddress.Element(ns + "stateCode"),
postCode = (string)mainBusinessPhysicalAddress.Element(ns + "postcode"),
isCurrentIndicator = (string)mainBusinessPhysicalAddress.Element(ns + "isCurrentIndicator"),
}
}).ToList();
searchPayload is a SOAP message returned from a web service and it returnes up to 200 searchResultRecords of which some of them have a mainName node, some legalNode, some all of the nodes and so on. If I use the code above I get the error in the topic because obviously not all result records have all nodes so how can I handle this?
In Name = new I want to get available “name” nodes
Thanks
I can’t see anything in the
lets that would through, sincenodeshould always be non-null. And outside thelets the only time you use it is inblah.Element(..)– so you have two choices:filter out the ones that won’t work (will remove data):
check before using
.Element(will default some fields to blank):