xml - 如何使用 XSLT 从子节点获取父节点

标签 xml xslt

我无法检索所有重复 child 名字的 parent 。

<NCAAScores>
   <levels>
      <level>
         <name>Western Conference</name>
         <teams>
            <team>
               <name>Dallas Stars</name>
               <scorable>
                  <win>60</win>
                  <lose>35</lose>
               </scorable>
            </team>
            <team>
               <name>Chicago Blackhawks</name>
               <scorable>
                  <win>60</win>
                  <lose>23</lose>
               </scorable>
            </team>
            <team>
               <name>Edmonton Oilers</name>
               <scorable>
                  <win>55</win>
                  <lose>9</lose>
               </scorable>
            </team>
            <team>
               <name>Philadelphia Flyers</name>
               <scorable>
                  <win>5</win>
                  <lose>9</lose>
               </scorable>
            </team>
         </teams>
      </level>
      <level>
         <name>Eastern Conference</name>
         <teams>
            <team>
               <name>Dallas Stars</name>
               <scorable>
                  <win>1</win>
                  <lose>34</lose>
               </scorable>
            </team>
<!---And so on, you get the idea-->  
         </teams>
      </level>
  </levels>
</NCAAScores>

如果我想检索拥有“达拉斯星队”球队的所有父级别,该方法是什么?

我尝试了以下

./levels[/level/teams/team/name = 'Dallas Stars']

,这没有帮助。

最佳答案

请尝试以下模板。这使用 ancestor:: 轴从当前节点上下文中查找 level/name

<xsl:template match="level">
    <xsl:for-each select="teams/team[name='Dallas Stars']">
        <name>
            <xsl:value-of select="ancestor::level/name" />
        </name>
    </xsl:for-each>
</xsl:template>

或者,您也可以使用

<xsl:value-of select="../../name" />

从当前节点上下文向上提升级别,但为了便于理解,我更喜欢使用ancestor

输出

<name>Western Conference</name>
<name>Eastern Conference</name>

关于xml - 如何使用 XSLT 从子节点获取父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50440708/

相关文章:

android - 与 xml 图形布局相比,模拟器上的按钮位置不正确

android - 抽屉导航选项位于布局下方

xml - 如何使用 vbscript 在现有 xml 中添加属性

java - 如何使用 Selenium 注入(inject) XML 文件?

c++ - QXmlQuery - 将参数传递给 XSLT

xml - 带有超棒字体的 jsTree 树中的节点图标

java - 严重 : Error configuring application listener of class org. apache.struts2.tiles.StrutsTilesListener java.lang.NoClassDefFoundError:

xml - xslt 将位置作为参数传递会产生奇怪的结果?

templates - xsl :fo template match not firing on nested list

XSLT : Merge duplicate scenario