C# 如何使用后代方法检查具有直接祖先的节点?
如何获取其直接祖先是另一个节点的节点的值(使用C# 如何使用后代方法检查具有直接祖先的节点?,c#,linq-to-xml,C#,Linq To Xml,如何获取其直接祖先是另一个节点的节点的值(使用子节点方法),e.x.下面是xml文件的一小部分 <sec id="s2"> <label>2.</label> <title>THE MORPHOLOGY OF CHONDRAE TENDIANEAE OF ATRIOVENTRICULAR VALVES HEARTS NEWBORNS AND INFANTS</title> <p>According to the mac
子节点
方法),e.x.下面是xml文件的一小部分
<sec id="s2">
<label>2.</label>
<title>THE MORPHOLOGY OF CHONDRAE TENDIANEAE OF ATRIOVENTRICULAR VALVES HEARTS NEWBORNS AND INFANTS</title>
<p>According to the macroscopic</p>
<fig id="F1">
<label>Figure 1.</label>
<caption><p>Tendon string valvular heart baby infants. 1 - mastoid muscle, 2 - tendon strings.</p></caption>
<graphic xlink:href="00062_psisdg9066_90661R_page_2_1.jpg"/>
</fig>
<fig id="F2">
<label>Figure 2.</label>
<caption><p>Tendon string valvular heart newborn baby. 1 - mastoid muscle, 2 - tendon strings.</p></caption>
<graphic xlink:href="00062_psisdg9066_90661R_page_2_2.jpg"/>
</fig>
</sec>
<sec id="s3">
<label>3.</label>
<title>EXPERIMENTAL RESULTS AND DISCUSSION</title>
<p>Material studies provided three-sided and mitral valve that were taken from 8 hearts of stillborn children and four dead infants.</p>
</sec>
我得到了2.,图1.,图2.,3。
,我还需要添加哪些条件才能实现我想要的?祖先(“sec”)
将找到所有祖先,不管嵌套有多深,而不是直接祖先,所以这不会有帮助。你只需要得到第一个祖先。由于
祖先()
将以相反的文档顺序返回它们,因此我们只需获取第一个
var x = from a in doc.Descendants("label")
let ancestor = a.Ancestors().First()
where ancestor.Name == "sec" && ancestor.Attributes("id").Any()
select a.Value;
谢谢。顺便说一句,在这种情况下,如何检查
x
是否为null/empty,如果(x==null){Console.WriteLine(“找不到这样的值!”);}
似乎不正确work@Bumbax
将不为空,但可以为空。因此,您可以使用DefaultIfEmpty()
var x = from a in doc.Descendants("label")
let ancestor = a.Ancestors().First()
where ancestor.Name == "sec" && ancestor.Attributes("id").Any()
select a.Value;