[英]Find elements by attribute name and its value using XDocument
Well, using .NET 3.5 and XDocument I am trying to find <table class='imgcr'>
element. 好吧,使用.NET 3.5和XDocument,我试图找到
<table class='imgcr'>
元素。 I created the code below but it crashes, of course, because e.Attribute("class")
may be null. 我在下面创建了代码,但是由于
e.Attribute("class")
可能为null,所以它崩溃了。 So... I have to put null check everywhere? 所以...我必须在所有地方都放空检查吗? This will double
e.Attribute("class")
. 这将使
e.Attribute("class")
翻倍。 Not laconic solution at all. 根本不是简单的解决方案。
XElement table =
d.Descendants("table").
SingleOrDefault(e => e.Attribute("class").Value == "imgcr");
If you are sure you exception is thrown because you table
element may come without class
attribute, then you could do this instead: 如果您确定由于
table
元素可能没有class
属性而引发异常,那么您可以这样做:
XElement table =
d.Descendants("table").
SingleOrDefault(e => ((string)e.Attribute("class")) == "imgcr");
In that case you are casting a null
value to string
, which is null
at the end, so you are comparing null == "imgcr"
, what is false
. 在这种情况下,您将
null
值强制转换为string
, null
处为null
,因此您将比较null == "imgcr"
,这是false
。
You can check this msdn page if you need more info about how to retrieve the value of an attribute. 如果需要有关如何检索属性值的更多信息,可以检查此msdn页面 。 There you will find this affirmation:
在那里,您将获得以下确认:
You can cast an
XAttribute
to the desired type;您可以将
XAttribute
转换为所需的类型。 the explicit conversion operator then converts the contents of the element or attribute to the specified type.然后,显式转换运算符将元素或属性的内容转换为指定的类型。
I guess this is quite short 我想这很短
XElement table =
d.Descendants("table").
SingleOrDefault(e => { var x = e.Attribute("class"); return x==null ? false: x.Value == "imgcr";});
this is shorter (but not much -- unless you can re-use t variable.) 这更短(但不多-除非您可以重新使用t变量。)
XAttribute t = new XAttribute("class","");
XElement table =
d.Descendants("table").
SingleOrDefault(e => (e.Attribute("class") ?? t).Value == "imgcr");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.