开发者

how to use xsl to distinguish two similar tags (variables)

I need to create a xsl able to read two xml files, which have the same structure except by the first tag:

inbound xml:

<beans:beans> <fix-inbound> <message></message>开发者_运维问答; </fix-inbound> </beans:beans>

outbound xml:

<beans:beans> <fix-outbound> <message></message> </fix-outbound> </beans:beans>

the solutions I could find out were:

  • creating two files to read the inbound and outbound
  • an awful if like :

    <xsl:if test="fix-inbound">
        code to read the content
    </xsl:if>
    <xsl:if test="fix-outbound"> 
        same piece of code to read the content 
    </xsl:if>
    
  • using a variable in my <xsl:for-each select="$valueOfMyFirstTag"> which the value of the variable could be fix-inbound or fix-outbound

However, I have no idea how to get the value of the first tag. Is that possible using xsl?

Is there a more elegant way to solve this problem?


You could use

<xsl:for-each select="/*/fix-inbound | /*/fix-outbound">

(or depending on your use case, use apply-templates instead of for-each).


It's not at all clear what you are trying to do or where you are failing, but it does appear from your post that you haven't yet discovered the joy of template rules, which form the heart of true XSLT processing. Perhaps you also haven't yet discovered the power of wildcards (*) in paths, or the "//" pseudo-operator.


Use:

<xsl:template match="/">
 <xsl:apply-templates select="/*/*[1]"/>
</xsl:template>

<xsl:template match="fix-inbound">
 <!-- Perform whatever processing is necessary  -->
</xsl:template>

<xsl:template match="fix-outbound">
 <!-- Perform whatever processing is necessary  -->
</xsl:template>

Explanation:

The <xsl:apply-templates select="/*/*[1]"/> instruction causes whatever template best matches the first child element of the top element to be selected for execution and applied.

If the document is of the first type, the template matching fix-inbound is applied.

If the document is of the second type, the template matching fix-outbound is applied.

Do note: No conditional instructions are used at all in this solution -- in XSLT they are rarely necessary and if conditional instructions are present, this is a signal that some refactoring may be appropriate.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜