首页 文章

XSL动态节点参考

提问于
浏览
1

我是XSL的新手,我正在尝试使用模板从XML文件动态引用节点 .

为了提供更多信息,我使用Cast Iron生成初始XML,并返回多个结果集,其中一些具有多行 . 示例XML如下:

<resultSets>
    <resultSet/>
    <resultSet>
      <row>
        <column1>1</column1>
        <column2>Hello</column2>
      </row>
    </resultSet>
    <resultSet>
      <row>
        <column1/>
      </row>
      <row>
        <column1/>
      </row>
    </resultSet>
</resultSets>

所以我试图将其转化为可供客户使用的东西 . 我想过使用带有一些输入的模板来让我的生活更轻松 .

我想设计一个模板,通过输入结果集的数字,行的数字和列的名称,它将引用数据 . 问题是,当我引用它时,结果节点不会被创建 . 所以我的问题是: How do I reference a Param as an Xml Node?

这是我对模板的看法:

<xsl:template name="getData">
    <xsl:param name="resultset" select="0" />
    <xsl:param name="position" select="0" />
    <xsl:param name="column-name" select="''" />
    <!-- Checking to see if Parameters were passed in.  This seems to work correctly -->
    <xsl:if test="($resultset &gt; 0)and($position &gt; 0)and($column-name != '')">
        <!-- Check to see if there are any rows in the resultSet.  This seems to work correctly -->
        <xsl:if test="count(//resultSets/resultSet[position() = $resultset]/row[position() = $position]) &gt; 0">
            <!-- This part fails; nothing is referenced --> 
            <xsl:value-of select="//resultSets/resultSet[position() = $resultset]/row[position() = $position][@name = $column-name]"/>
        </xsl:if>
    </xsl:if>
</xsl:template>

以下是我尝试引用它的方法(作为示例):这应该从XML文件返回'Hello'(不应该吗?)

<xsl:element name="SampleElement">
 <xsl:call-template name="getData">
  <xsl:with-param name="resultset" select="2" />
  <xsl:with-param name="position" select="1" /> 
  <xsl:with-param name="column-name" select="'column2'" />
 </xsl:call-template>
</xsl:element>

对不起,如果我的问题不清楚或之前被问过,我什么都没发现 .

1 回答

  • 1

    Simply use

    <xsl:value-of select=
      "/*/resultSet[position()=$resultset]
            /row[position()=$position]
              /*[name()=$column-name]"/>
    

    Do note XPath中的索引是基于1的 - 不是基于0的 .

    Complete transformation

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="text"/>
    
      <xsl:param name="pResSetNo" select="2"/>
      <xsl:param name="pRowNo" select="1"/>
      <xsl:param name="pColName" select="'column2'"/>
    
    
        <xsl:template match="/">
          <xsl:copy-of select=
          "/*/resultSet[position()=$pResSetNo]
            /row[position()=$pRowNo]
              /*[name()=$pColName]"/>
        </xsl:template>
    </xsl:stylesheet>
    

    When this transformation is applied on the provided XML document:

    <resultSets>
        <resultSet/>
        <resultSet>
          <row>
            <column1>1</column1>
            <column2>Hello</column2>
          </row>
        </resultSet>
        <resultSet>
          <row>
            <column1/>
          </row>
          <row>
            <column1/>
          </row>
        </resultSet>
    </resultSets>
    

    the wanted, correct result is produced

    Hello
    

相关问题