xslt模板v1,v2中的复杂变量

时间:2014-07-15 09:12:59

标签: xslt

我有源xml看起来像这样:

<Data>
 <ActionPlaces>
   <ActionPlace>
        <ActionPlaceID>74</ActionPlaceID>
        <PlaceName>Theatre Of Classic</PlaceName>
   </ActionPlace>  
 </ActionPlaces>
 <Actions>
  <CommonAction Id="2075" Name="King">
      <Action>
         <ActionID>4706</ActionID>
         <ActionPlaceID>74</ActionPlaceID>
       </Action>
  </CommonAction>
 </Actions>
</Data>

要转变为:

<category name="King">
 <name>King</name>
 <parent name="Theatre Of Classic" />
</category>

我想使用变量:

<xsl:template match="ActionPlaces">
 <xsl:variable name="id" select="/ActionPlace/ActionPlaceID"/>

<xsl:template match="CommonAction" > 
 <category name="<xsl:value-of select="@name"/> >
    <name><xsl:value-of select="@name"/></name> 
    <parent <xsl:if test="/Action/ActionPlaceID = $id">
    name=/Action/ActionPlaceID/> <- how to get name of theatre here?
</xsl:template>

变量存储不仅可以存储ID,还可以存储名称吗?以及如何获得它?处理此问题的最常用方法是什么?

1 个答案:

答案 0 :(得分:2)

这是使用XSL密钥的一个选项(如@ michael-hor257k建议的那样):

输入

<Root>
  <ActionPlaces>
    <ActionPlace>
      <ActionPlaceID>74</ActionPlaceID>
      <PlaceName>Theatre Of Classic</PlaceName>
    </ActionPlace>
  </ActionPlaces>
  <Actions>
    <CommonAction Id="2075" Name="King">
      <Action>
        <ActionID>4706</ActionID>
        <ActionPlaceID>74</ActionPlaceID>
      </Action>
    </CommonAction>
  </Actions>
</Root>

样式表

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

  <!-- Collect all <ActionPlace> elements into an XSL key -->
  <xsl:key name="ActionPlaceById" match="ActionPlace" use="ActionPlaceID"/>

  <xsl:template match="/">
    <xsl:apply-templates select="Root/Actions/CommonAction"/>
  </xsl:template>

  <xsl:template match="CommonAction">
    <category name="{@Name}">
      <name>
        <xsl:value-of select="@Name"/>
      </name>

      <!--
      Using the ActionPlaceById key we created earlier, fetch the <ActionPlace>
      element that has an <ActionPlaceID> child that has the same value as the
      <ActionPlaceID> descendant of the current <CommonAction> element.
      -->
      <parent name="{key('ActionPlaceById', Action/ActionPlaceID)/PlaceName}"/>
    </category>
  </xsl:template>
</xsl:stylesheet>

输出

<?xml version="1.0" encoding="utf-8"?>
<category name="King">
  <name>King</name>
  <parent name="Theatre Of Classic"/>
</category>