XSLT索引基于输出,而不是输入

时间:2011-12-20 15:46:28

标签: xslt

我有一些源XML包含不同的元素,这些元素由样式表转换为具有相同名称的输出元素。然后输出元素在每个元素上都需要一个'index'元素。 我的第一个选择是使用position(),但当然这只适用于xsl:for-each的上下文。

以下是XML示例:

<Root>
    <TypeA Val="First Value"/>
    <TypeA Val="Second Value"/>
    <NotToBeTransformed Val="ignoreme"/>
    <TypeB Val="Third Value"/>
    <TypeB Val="Fourth Value"/>
</Root>

以下是我希望将其呈现为输出的方式:

<Output>
    <Destination>
        <Index>1</Index>
        <Content>First Value</Content>
    </Destination>
    <Destination>
        <Index>2</Index>
        <Content>Second Value</Content>
    </Destination>
    <Destination>
        <Index>3</Index>
        <Content>Third Value</Content>
    </Destination>
    <Destination>
        <Index>4</Index>
        <Content>Fourth Value</Content>
    </Destination>
</Output>

我的简单XSLT如下:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:template match="/">
    <Output>
        <xsl:for-each select="//TypeA">
            <Destination>
                <Index><xsl:value-of select="position()"/></Index>
                <Content><xsl:value-of select="@Val"/></Content>
            </Destination>
        </xsl:for-each>
        <xsl:for-each select="//TypeB">
            <Destination>
                <Index><xsl:value-of select="position()"/></Index>
                <Content><xsl:value-of select="@Val"/></Content>
            </Destination>
        </xsl:for-each>
    </Output>
</xsl:template>

但是,对于每个源元素集合,它输出值为1和2的索引。 这可以在XSLT中完成还是需要再次处理?我正在使用C#代码进行转换,因此我可以运行初始转换,然后在代码中设置索引值。

任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:2)

您根本不需要使用xsl:for-each(请尽量避免使用它),也无需单独处理TypeATypeB元素。

此转化

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/*">
  <Output>
   <xsl:apply-templates select="TypeA|TypeB"/>
  </Output>
 </xsl:template>
 <xsl:template match="*/*">
    <Destination>
        <Index><xsl:value-of select="position()"/></Index>
        <Content><xsl:value-of select="@Val"/></Content>
    </Destination>
 </xsl:template>
</xsl:stylesheet>

应用于提供的XML文档

<Root>
    <TypeA Val="First Value"/>
    <TypeA Val="Second Value"/>
    <NotToBeTransformed Val="ignoreme"/>
    <TypeB Val="Third Value"/>
    <TypeB Val="Fourth Value"/>
</Root>

生成想要的正确结果

<Output>
   <Destination>
      <Index>1</Index>
      <Content>First Value</Content>
   </Destination>
   <Destination>
      <Index>2</Index>
      <Content>Second Value</Content>
   </Destination>
   <Destination>
      <Index>3</Index>
      <Content>Third Value</Content>
   </Destination>
   <Destination>
      <Index>4</Index>
      <Content>Fourth Value</Content>
   </Destination>
</Output>
相关问题