如何识别特定元素下具有特定位置的元素

时间:2016-03-09 07:31:09

标签: xslt xslt-2.0

请建议如何找到'mfrac'在其第二个子方面的'msup'元素下。 (Mfenced是mfenced,当它包含'mfrac作为其后代,但仅当 mfrac在msup的第二个子位置下找到时,则应该转换为' mo '。)< / p>

  • 当mfrac在'msup'的第一个子区域内时,则'mfenced'为否 需要改变。
  • 当mfrac在'msup'的第二个孩子一侧时,那么'mfenced' 是转换为' mo '
  • 否则'mfrac'在'mfenced'中找到,然后'mfenced'是没有必要的 改变。

XML:

<article>
<math><mfenced open="(" close=")"><mfrac><mn>1</mn><mn>2</mn></mfrac></mfenced></math>
<math><mfenced open="(" close=")"><msup><mfrac><mn>1</mn><mn>2</mn></mfrac><mn>7</mn></msup></mfenced></math>
<math><mfenced open="(" close=")"><msup><mn>7</mn><mfrac><mn>1</mn><mn>2</mn></mfrac></msup></mfenced></math>
<math><mfenced open="(" close=")"><msup><mrow><mn>7</mn></mrow><mrow><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow></msup></mfenced></math>
</article>

XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@* | node()"/></xsl:copy>
</xsl:template>

<xsl:template match="mfenced">
    <xsl:choose>
        <xsl:when test="not(descendant::mfrac[. is ancestor::msup[1]/*[1]/descendant::*])"><!--checking, whether mfrac not found within first child of 'msup' -->
            <mo><xsl:apply-templates/></mo>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy><xsl:apply-templates select="@* | node()"/></xsl:copy>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>

必填结果:

<article>
<math><mfenced open="(" close=")"><mfrac><mn>1</mn><mn>2</mn></mfrac></mfenced></math><!--no need alter, because 'mfrac' found within 'mfenced'-->
<math><mfenced open="(" close=")"><msup><mfrac><mn>1</mn><mn>2</mn></mfrac><mn>7</mn></msup></mfenced></math><!--no need alter, because 'mfrac' found within first child of 'msup' -->
<math><mo><msup><mn>7</mn><mfrac><mn>1</mn><mn>2</mn></mfrac></msup></mo></math><!--Converted to 'MO', because 'mfrac' is under 2nd child of 'msup' -->
<math><mo><msup><mrow><mn>7</mn></mrow><mrow><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow></msup></mo></math><!--Converted to 'MO', because 'mfrac' is under 2nd child of 'msup' -->
</article>

错误讯息:

  XPTY0004: A sequence of more than one item is not allowed as the second operand of 'is' (<mn/>, <mn/>)

1 个答案:

答案 0 :(得分:1)

怎么样:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy><xsl:apply-templates select="@* | node()"/></xsl:copy>
    </xsl:template>

    <xsl:template match="mfenced[
        not(mfrac)
        and (
            msup/mfrac[preceding-sibling::*]
            or msup//mfrac[not(parent::msup)]
        )
    ]">
        <mo><xsl:apply-templates/></mo> 
    </xsl:template>
</xsl:stylesheet>