Xslt 为每个循环嵌套,使用来自内部循环的变量访问外部元素
我正在尝试编写一个XSL,它将从源XML输出特定字段子集。该子集将在转换时通过使用包含字段名和其他特定信息(如填充长度)的外部XML配置文档来确定 因此,每个循环有两个Xslt 为每个循环嵌套,使用来自内部循环的变量访问外部元素,xslt,variables,xpath,foreach,Xslt,Variables,Xpath,Foreach,我正在尝试编写一个XSL,它将从源XML输出特定字段子集。该子集将在转换时通过使用包含字段名和其他特定信息(如填充长度)的外部XML配置文档来确定 因此,每个循环有两个: 外部的一个遍历记录,逐个记录访问它们的字段 内部的一个遍历配置XML文档,从当前记录中获取配置的字段 我已经看到,外部循环中的当前元素可以存储在xsl:variable中。但是我必须在内部循环中定义一个新变量来获取字段名。这就引出了一个问题:是否有可能访问一条包含两个变量的路径 例如,源XML文档如下所示: <dat
:
- 外部的一个遍历记录,逐个记录访问它们的字段
- 内部的一个遍历配置XML文档,从当前记录中获取配置的字段
我已经看到,外部循环中的当前元素可以存储在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>
价值1
...
瓦伦
价值1
...
瓦伦
我想要一个外部XML文件,如下所示:
<configuration>
<outputField order="1">
<fieldName>field1</fieldName>
<fieldPadding>25</fieldPadding>
</outputField>
...
<outputField order="N">
<fieldName>fieldN</fieldName>
<fieldPadding>10</fieldPadding>
</outputField>
</configuration>
字段1
25
...
菲尔登
10
到目前为止,我得到的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非常陌生,因此这可能是一个荒谬的问题,而且这种方法也可能是完全错误的(即,对于一次可以完成一次的任务,重复内部循环)。如果您能给我一些提示,告诉我如何从外部循环元素中选择字段值,当然,也可以找到更好的方法来完成这项任务。您的样式表看起来很不错。只有表达式$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>
<xsl:variable name="value" select="$rec/*[name(.)=current()/fieldName]"/>