如何转换xslt - >这个文件的HTML

时间:2017-06-21 12:34:14

标签: html xml xslt

XML

  <?xml version='1.0' encoding='UTF-8'?>
    <folder>
    <document>
            <h1>Harry Potter</h1>
            <h2>j.rowling</h2>
            <subheading>book</subheading>
        </document>
        <document>
            <p type="num">
                <num>55</num>           
            </p>
            <h1>Hi-Tech</h1>
        </document>
    </folder>

我不能这样做:

  1. 如果找到元素h1,h2,subheading的顺序,则在一行上显示h1和子标题,然后输出元素h2;
  2. 现在:

       <document>
            <h1>Harry Potter</h1>
            <h2>j.rowling</h2>
            <subheading>book</subheading>
        </document>
    

    应该是:

       <div class="document">
            <h1 style="display:inline-block">Harry Potter book </h1>
            <h5 style="display:inline-block">book</h5>
            <br/>
            <h2>j.rowling</h2>
        </div>
    
    1. 如果在h1元素之前有一个元素“p”,其属性为type =“num”,其中没有空元素num - 将其显示在一行中,元素为h1。

2 个答案:

答案 0 :(得分:1)

首先考虑第一个要求,如果您知道输入具有序列(h1,h2,副标题),则可以使用此逻辑轻松完成:

<xsl:template match="document">
  <div class="document">
    <xsl:apply-templates select="h1"/>
    <xsl:apply-templates select="subheading"/>
    <br/>
    <xsl:apply-templates select="h2"/>
  </div>
</xsl:template>

<xsl:template match="h1"/>
  <h1 style="display:inline-block"><xsl:value-of select="."/></h1>
</xsl:template>

<xsl:template match="h2"/>
  <h2><xsl:value-of select="."/></h2>
</xsl:template>

<xsl:template match="subheading"/>
  <h5 style="display:inline-block"><xsl:value-of select="."/></h5>
</xsl:template>

然后问题出现了:如果它不是这种格式怎么办?不幸的是,您还没有告诉我们其他格式是什么,以及遇到它们时想要生成什么。因此,如果没有更多信息,我们就无法继续这样做。

第二条规则可以转换为XSLT

<xsl:template match="h1[preceding-sibling::*[1][self::p/@num][not(child::num)]">
  <h1>
   <xsl:value-of select="preceding-sibling::*[1][self::p/@num]/@num"/>
   <xsl:value-of select="."/>
  </h1>
</xsl:template>

答案 1 :(得分:0)

我做到了!

我的解决方案基于 运算符

*我的工作解决方案:*

<xsl:template match="document[h1 and h2 and subheading]">
  <xsl:value-of select="concat(h1,' ',subheading)"/>
  <br/>
  <xsl:value-of select="h2"/>
</xsl:template>

<xsl:template match="document[p[@type='num'][num] and h1]">  
  <xsl:value-of select="concat(h1,' ',p)"/>
</xsl:template>