开发者

XSLT:How to deal with testing the value of an element?

I have an xml file in which there is tag namely, <Gender/> It carries either 'M' or 'F' as data, now my work is to test the value and write &l开发者_运维技巧t;Gender_Tag>Male</Gender_Tag> or <Gender_Tag>Female</Gender_Tag> according to the values M or F respectively .. I tried this code .. It used to work in other circumstances..


All relative paths expressed in a template are evaluated against the current node. Your template match Gender elements, so Gender='M' returns true if there is any Gender's child named 'Gender' with the value 'M'. I guess this is not the case...

Use the dot to express the current node (here a Gender element):

<xsl:template match="root/details/Gender">
  <Gender_Tag>  
    <xsl:choose>
      <xsl:when test=".='M'">
        <xsl:text>Male</xsl:text>
      </xsl:when>
      <xsl:otherwise>
       <xsl:text>Female</xsl:text>
      </xsl:otherwise>
    </xsl:choose>
  </Gender_Tag>
</xsl:template>

EDIT: You may use two templates too

<xsl:template match="root/details/Gender[.='M']">
  <Gender_Tag>Male</Gender_Tag>
</xsl:template>
<xsl:template match="root/details/Gender[.='F']">
  <Gender_Tag>Female</Gender_Tag>
</xsl:template>


Untested, but may work...

<xsl:template match="root/details/Gender">
  <xsl:if test="text()='M'">
    <Gender_Tag>Male</Gender_Tag>
  </xsl:if>
  <xsl:if test="text()='F'">
    <Gender_Tag>Female</Gender_Tag>
  </xsl:if>
</xsl:template>


<xsl:template match="root/details/Gender">
    <xsl:choose>
        <xsl:when test="normalize-space(text())='M'">
            <Gender_Tag>Male</Gender_Tag>
        </xsl:when>
        <xsl:otherwise>
            <Gender_Tag>Female</Gender_Tag>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

My example differs in two points from Scoregraphic's:

  1. It uses xsl:choose to ensure, that only one Gender_Tag element is created (that also means, that if the text is not 'M', it is always a Female)

  2. Use of normalize-space() strips white space around the text content of the element.


Without seeing XML its hard to be certain, but I think your sample XSLT should be:

<xsl:template match="root/details/Gender">    
   <xsl:if test=".='M'">
      <Gender_Tag><xsl:text>Male</xsl:text></Gender_Tag>
   </xsl:if>
   <xsl:if test=".='F'">
      <Gender_Tag><xsl:text>Female</xsl:text></Gender_Tag>
   </xsl:if>
</xsl:template>

Use of choose as per another answer would be better (though I think it should be two explicit when clauses rather than a when and an otherwise)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜