如何使用后代方法检查具有直接祖先的节点?

How to check for a node with a immediate ancestor using descendants method?

如何获取其直接祖先是另一个节点的节点的值(使用 descendants 方法),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>

我想要具有直接祖先节点 <sec> 的节点 <label> 的所有值。即在这种情况下,值应为 2.3. 如果我这样做

XDocument doc=XDocument.Load(@"D:\test\sample.XML");
var x = from a in doc.Descendants("label")
        where a.Ancestors("sec").Attributes("id").Any()
        select a.Value;

我得到了2., Figure 1., Figure 2., 3.,我还需要添加什么其他条件才能实现我想要的?

Ancestors("sec") 将找到所有祖先,无论嵌套有多深,而不是直接祖先,所以这没有帮助。
你只需要得到第一个祖先。由于 Ancestors() 将 return 它们以相反的文档顺序排列,我们可以简单地获取第一个。

var x = from a in doc.Descendants("label")
    let ancestor = a.Ancestors().First()
    where ancestor.Name == "sec" && ancestor.Attributes("id").Any()
    select a.Value;