我有以下代码来获取有关公司的一些数据:
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是从Web服务返回的SOAP消息,它返回最多200个searchResultRecords,其中一些有一个mainName节点,一些legalNode,一些所有节点,依此类推。如果我使用上面的代码,我会在主题中得到错误,因为显然并非所有结果记录都包含所有节点,所以我该如何处理?
在Name = new中我希望获得“名称”节点
由于
答案 0 :(得分:1)
我无法在let
中看到任何内容,因为node
应始终为非空。而外 let
s唯一一次使用它是blah.Element(..)
- 所以你有两个选择:
过滤掉那些无效的(将删除数据):
....
let mainTradingName = node.Element(ns + "mainTradingName")
where mainTradingName != null
....
在使用.Element
之前检查(默认某些字段为空白):
...
organisationName = mainTradingName == null ? "" :
(string)mainTradingName.Element(ns + "organisationName"),
...