14

我正在尝试编写一个 XSL,它将从源 XML 输出某个字段子集。该子集将在转换时通过使用包含字段名称和其他特定信息(例如填充长度)的外部 XML 配置文档来确定。

所以,这是两个for-each循环:

  • 外层遍历记录以逐条记录访问其字段。
  • 内层遍历配置 XML 文档以从当前记录中获取配置的字段。

在 XSLT 中看到如何从嵌套循环中访问外部循环中的元素?外部循环中的当前元素可以存储在xsl:variable. 但是我必须在内部循环中定义一个新变量来获取字段名称。这产生了一个问题:是否可以访问有两个变量的路径?

例如,源 XML 文档如下所示:

<data>
    <dataset>
        <record>
            <field1>value1</field1>
            ...
            <fieldN>valueN</fieldN>
        </record>
    </dataset>
    <dataset>
        <record>
            <field1>value1</field1>
            ...
            <fieldN>valueN</fieldN>
        </record>
    </dataset>
</data>

我想要一个看起来像这样的外部 XML 文件:

<configuration>
    <outputField order="1">
        <fieldName>field1</fieldName>
        <fieldPadding>25</fieldPadding>
    </outputField>
    ...
    <outputField order="N">
        <fieldName>fieldN</fieldName>
        <fieldPadding>10</fieldPadding>
    </outputField>
</configuration>

到目前为止我得到的 XSL:

<xsl:variable name="config" select="document('./configuration.xml')"/>
<xsl:for-each select="data/dataset/record">
    <!-- Store the current record in a variable -->
    <xsl:variable name="rec" select="."/>
    <xsl:for-each select="$config/configuration/outputField">
        <xsl:variable name="field" select="fieldName"/>
        <xsl:variable name="padding" select="fieldPadding"/>

        <!-- Here's trouble -->
        <xsl:variable name="value" select="$rec/$field"/>

        <xsl:call-template name="append-pad">
            <xsl:with-param name="padChar" select="$padChar"/>
            <xsl:with-param name="padVar" select="$value"/>
            <xsl:with-param name="length" select="$padding"/>
        </xsl:call-template>

    </xsl:for-each>
    <xsl:value-of select="$newline"/>
</xsl:for-each>

我对 XSL 很陌生,所以这很可能是一个荒谬的问题,而且这种方法也可能是完全错误的(即重复内循环的任务可以在开始时完成一次)。对于如何从外部循环元素中选择字段值的任何提示,我将不胜感激,当然,我也愿意接受更好的方法来处理此任务。

4

1 回答 1

15

您的样式表看起来几乎没问题。只是表达式$rec/$field没有意义,因为您不能以这种方式组合两个节点集/序列。相反,您应该使用该name()函数比较元素的名称。如果我正确理解了你的问题,这样的事情应该可以工作:

<xsl:variable name="config" select="document('./configuration.xml')"/>
<xsl:for-each select="data/dataset/record">
    <xsl:variable name="rec" select="."/>
    <xsl:for-each select="$config/configuration/outputField">
        <xsl:variable name="field" select="fieldName"/>
        ...
        <xsl:variable name="value" select="$rec/*[name(.)=$field]"/>
        ...    
    </xsl:for-each>
    <xsl:value-of select="$newline"/>
</xsl:for-each>

此示例中不需要变量字段。您还可以使用函数current()访问内部循环的当前上下文节点:

<xsl:variable name="value" select="$rec/*[name(.)=current()/fieldName]"/>
于 2012-05-03T17:36:37.083 回答