C# 使用XDocument按属性名及其值查找元素
使用.NET3.5和XDocument,我试图找到C# 使用XDocument按属性名及其值查找元素,c#,linq-to-xml,C#,Linq To Xml,使用.NET3.5和XDocument,我试图找到元素。我创建了下面的代码,但它崩溃了,因为e.Attribute(“class”)可能为空。所以我必须把空支票放在所有地方?这将加倍e.Attribute(“class”)。一点也不简洁 XElement table = d.Descendants("table"). SingleOrDefault(e => e.Attribute("class").Value == "imgcr"); 我想这很短 XElement ta
元素。我创建了下面的代码,但它崩溃了,因为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变量)
如果您确信由于
table
元素可能没有class
属性而引发异常,那么您可以这样做:
XElement table =
d.Descendants("table").
SingleOrDefault(e => ((string)e.Attribute("class")) == "imgcr");
在这种情况下,您将null
值强制转换为string
,该值在末尾为null
,因此您将比较null==“imgcr”
,什么是false
如果需要有关如何检索属性值的更多信息,可以选中此选项。在那里你会发现这样的肯定:
您可以将XAttribute
强制转换为所需类型;明确的
然后转换运算符转换元素或元素的内容
属性设置为指定的类型
XElement table =
d.Descendants("table").
SingleOrDefault(e => ((string)e.Attribute("class")) == "imgcr");