首页 > 解决方案 > 为什么我会看到另一个位置的值 (xslt)?

问题描述

抱歉这个菜鸟问题,我已经通过添加不是很优雅的空模板解决了这个问题,但是谁能帮助我理解为什么我一直在输出中看到另一个“级别”的值?

这就是我的 xml 的样子:

<root>
 <offers>
  <theme>
    <type>theme1</type>
    <name>...</name>
    <slug>...</slug>
    <description>...</description>
    <total>32</total>
    <url_title>...</url_title>
    <url_anchor>...</url_anchor>
    <url>...</url>
    <offers>
      <row>
        <offer>
          <name>travel</type>
          <id>68232</id>
   </theme>
   <theme>
    <type>theme2</type>
    <name>...</name>
    <slug>...</slug>
    <description>...</description>
    <total>32</total>
    <url_title>...</url_title>
    <url_anchor>...</url_anchor>
    <url>...</url>
    <offers>
      <row>
        <offer>
          <name>clowns</type>
          <id>222</id>
   </theme>
 </offers>
</root>

每个主题仅提供 1 个优惠。我想并排显示来自主题/优惠/行/优惠的优惠,所以我使用了:

<xsl:template match="root/offers">
    <xsl:apply-templates select="theme[position() mod 2 = 1]" mode="row" />
</xsl:template>

<xsl:template match="theme" mode="row">
    <xsl:apply-templates select="offers/row/offer/." mode="offer1" />
    <xsl:apply-templates select="following-sibling::theme[1]" mode="offer2" />
</xls:template>

<xsl:template match="*" mode="offer1">
=== This one showed the offer correctly 
</template>

<xsl:template match="offer" mode="offer2">
=== This one kept showing the 'type', 'name' 'slug' 
=== values from the theme node, 
=== even though I didn't ask for them
</xsl:template>

我只是通过添加空模板来修复它,如下所示:

<xsl:template match="theme/type" mode="offer2"/>
<xsl:template match="theme/name" mode="offer2"/>
<xsl:template match="theme/slug" mode="offer2"/>

我只是想了解我哪里出错了。我一直在摆弄兄弟语法(不能在那里使用'.'......)并且我需要在'主题'级别使用mod 2 = 1,因为每个主题只包含一个优惠。

标签: xmlxsltxslt-1.0

解决方案


由于内置模板规则而出现问题

让我们看看这个规则:

<xsl:template match="theme" mode="row">
    <xsl:apply-templates select="offers/row/offer/." mode="offer1" />
    <xsl:apply-templates select="following-sibling::theme[1]" mode="offer2" />
</xls:template>

请注意您如何应用模板来选择offer孙子和主题兄弟。所以,因为在模式中没有theme元素规则offer2,所以应用内置规则:元素应用节点子节点,输出文本节点。

这就是为什么转换(不是你说的规则)输出

'type', 'name', 'slug', 来自主题节点的值,即使我没有要求它们

更新:来自OP的评论

是啊,那我怎么丢掉它们,同时仍然配对

推送方式:将规则改为

<xsl:template match="theme" mode="row">
    <xsl:apply-templates 
         select="offers/row/offer" mode="offer1" />
    <xsl:apply-templates 
         select="following-sibling::theme[1]/offers/row/offer" mode="offer2" />
</xls:template>

拉取样式:添加此规则以覆盖模式中的文本节点内置规则'offer2'

<xsl:template match="text()" mode="offer2"/>

推荐阅读