2016-02-26 76 views
0

我有一个XML文件如下。如何使用XSL在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> 

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

在此先感谢。

+0

为什么你需要找到以前的标签?问题中添加您的xsl实验。 – vels4j

+0

您使用的xslt版本? – vels4j

+0

你有答案。如果你使用撒克逊,你可以有一个计数器验证条件。 – vels4j

回答

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> 
0

你唯一的错误是认为preceding-sibling::p意味着“直接前置兄弟是p”的时候,其实它的意思是“有在前面的兄弟姐妹中至少有一个p“。在您的测试中用preceding-sibling::*[1]/self::p代替preceding-sibling::p

Martin Honnen建议的结构更改(使用多个模板而不是一个)通常是一个好主意,但与您的代码的失败无关,因此无法提供您期望的结果。