XSLT transform with inline if statements

2019-07-11 15:54发布

I have some XML data that I want to convert to HTML with XSLT and I have mostly got it right. The problem with my XML input is that it contains inline if statements / boolean expressions that I have no idea how to handle.

<section>
  <title>My Title</title>
  <paragraph>
    <phrase class="inline-if">if_xVariable || if_yVariable</phrase>
    Show this text if if_xVariable or if_yVariable is true.
  </paragraph>
  <paragraph>
    <phrase class="inline-if">if_xVariable &amp;&amp; if_yVariable</phrase>
    Show this text if if_xVariable and if_yVariable is true
  </paragraph>
  <paragraph>
    Always show this text
  </paragraph>
</section>

I have been thinking of adding xslt-vairables with each variable name (e.g. if_xVariable) to true/false and in some way check against them.

How would you go about to solve this problem?

Update This is what I've tried

<xsl:template match="section/paragraph">
  <xsl:variable name="inlineif" select="phrase[@class='inline-if']"/>
    <xsl:if test="$inlineif">
      <p>
      <xsl:value-of select="."/>
      </p>
    </xsl:if>
</xsl:template>

Since I have neither of if_xVariable or if_yVariable specified, the output should probably be something like

<p>
Always show this text
</p>

but instead I get the output from all of the paragraphs.

标签: xml xslt
3条回答
smile是对你的礼貌
2楼-- · 2019-07-11 16:07

this is the code in xsl file

in tag

  <xsl:for-each select="persons/person">
  <xsl:if test="GenderElementType='combo'">
       <select name="gender">
      <option>
      <xsl:value-of select="Gender"/>
      </option>
      <xsl:if test="Gender='MALE'">
      <option>
       FEMALE
      </option>
      </xsl:if>
      <xsl:if test="Gender='FEMALE'">
      <option>
       MALE
      </option>
      </xsl:if>
      </select>
      </xsl:if>
 </xsl:for-each>

person.xml is as follow

 <persons>
 <person>
        <Gender>MALE</Gender>
    <GenderElementType>radio</GenderElementType>


</person>

查看更多
时光不老,我们不散
3楼-- · 2019-07-11 16:12

you can use following

<xsl:if test="expression">
    ...some output if the expression is true...
 </xsl:if>

full example is at http://www.w3schools.com/xsl/xsl_if.asp

查看更多
劳资没心,怎么记你
4楼-- · 2019-07-11 16:22

XSLT has no built-in dynamic evaluation of expressions. Possible solutions are discussed in the answer to this question.

查看更多
登录 后发表回答