如何使用XSL在xml中找到以前的标签?

时间:2016-02-26 11:22:32

标签: xml xslt

我有一个XML文件,如下所示。

<p>Sample Content 1</p>
<p>Sample Content 2</p>
<sec level="1">Sample Content 3</sec>
<p>Sample Content 4</p>
<p>Sample Content 5</p>

XSL转换:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="p">
 <xsl:choose>
  <xsl:when test="preceding-sibling::p">
   <p class="indent"><xsl:apply-templates /></p>
  </xsl:when>
  <xsl:otherwise>
   <p class="noindent"><xsl:apply-templates /></p>
  </xsl:otherwise>
 </xsl:choose>
</xsl:template>
</xsl:stylesheet>

我需要以下格式的输出。

<p class="noindent">Sample Content 1</p>
<p class="indent">Sample Content 2</p>
<h1>Sample Content 3</h1>
<p class="noindent">Sample Content 4</p>
<p class="indent">Sample Content 5</p>

请告诉上述概念的想法。所以我必须找出以前的标签格式..

提前致谢。

2 个答案:

答案 0 :(得分:2)

将条件移动到匹配模式并将条件更改为preceding-sibling::*[1][self::p]

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

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

    <xsl:template match="p">
        <p class="noindent">
            <xsl:apply-templates/>
        </p>
    </xsl:template>
    <xsl:template match="p[preceding-sibling::*[1][self::p]]">
        <p class="indent">
            <xsl:apply-templates/>
        </p>
    </xsl:template>
</xsl:transform>

答案 1 :(得分:0)

您唯一的错误是认为preceding-sibling::p表示“前一个兄弟姐妹是p”,而实际上它意味着“前面的兄弟姐妹中至少有一个p” 。在您的测试中,将preceding-sibling::p替换为preceding-sibling::*[1]/self::p

Martin Honnen建议的结构变化(使用多个模板而不是一个模板)通常是一个好主意,但与您的代码未能满足您的预期无关。

相关问题