var menuItems = from c in xMenuElement.Elements("GlobalNavigation").Elements("PrimaryLink")
where c.Element("SecondaryLink").Element("LeftMenu").Element("NavLinks").Element("LinkID").Value.Trim() == "sad1"
select c;
答案 0 :(得分:1)
试试这个,这个技术可以重复多次
var menuItems = from c in xMenuElement.Elements("GlobalNavigation").Elements("PrimaryLink")
let secondaryLink = c.Element("SecondaryLink")
where secondaryLink != null
&& secondaryLink.Element("LeftMenu").Element("NavLinks").Element("LinkID").Value.Trim() == "sad1"
select c;
否则你可以创建一个方法:
var menuItems = from c in xMenuElement.Elements("GlobalNavigation").Elements("PrimaryLink")
let linkId = GetLinkId(c)
where linkId != null
select c;
string GetLinkId(XElement element)
{
var secondaryLink = element.Element("SecondaryLink");
if (secondaryLink == null) return null;
var leftMenu = secondaryLink.Element("LeftMenu");
if (leftMenu== null) return null;
// ...
return linkId.Value;
}
如果您仍然收到空引用异常,则可能是您的来源存在问题。
var globalNav = xMenuElement.Elements("GlobalNavigation");
if (globalNav != null)
{
var primaryLinks = globalNav.Elements("PrimaryLink");
if (primaryLinks != null)
{
var menuItems = from c in primaryLinks //...
}
}