使用 XDocument 按属性名称及其值查找元素

Find elements by attribute name and its value using XDocument

好吧,我正在尝试使用 .NET 3.5 和 XDocument 查找 <table class='imgcr'> 元素。我创建了下面的代码,但它崩溃了,当然,因为 e.Attribute("class") 可能为空。所以......我必须到处检查空值吗?这将加倍 e.Attribute("class")。根本不是简洁的解决方案。

XElement table =
    d.Descendants("table").
    SingleOrDefault(e => e.Attribute("class").Value == "imgcr");

我想这很短

XElement table =
  d.Descendants("table").
    SingleOrDefault(e => { var x = e.Attribute("class"); return x==null ? false: x.Value == "imgcr";});

这个更短(但不多——除非你可以重新使用 t 变量。)

XAttribute t = new XAttribute("class","");
XElement table =
  d.Descendants("table").
    SingleOrDefault(e => (e.Attribute("class") ?? t).Value == "imgcr");

如果您确定因为 table 元素可能没有 class 属性而抛出异常,那么您可以改为这样做:

XElement table =
    d.Descendants("table").
    SingleOrDefault(e => ((string)e.Attribute("class")) == "imgcr");

在这种情况下,您将 null 值转换为 string,最后是 null,因此您正在比较 null == "imgcr",什么是 false.

如果您需要有关如何检索属性值的更多信息,可以查看此 msdn page。在那里你会发现这个肯定:

You can cast an XAttribute to the desired type; the explicit conversion operator then converts the contents of the element or attribute to the specified type.