枚举值基于不同的XSLT 2.0

时间:2009-03-12 17:38:03

标签: xml xslt xslt-2.0

我在XML中有一长串带有命名标识符的值列表。我需要为分组在一起且唯一命名的每个不同标识符创建单独的输出文件。

所以,例如,假设我有:

<List>
   <Item group="::this_long_and_complicated_group_name_that_cannot_be_a_filename::">
      Hello World!
   </Item>
   <Item group="::this_other_long_and_complicated_group_name_that_cannot_be_a_filename::">
      Goodbye World!
   </Item>
   <Item group="::this_long_and_complicated_group_name_that_cannot_be_a_filename::">
      This example text should be in the first file
   </Item>
   <Item group="::this_other_long_and_complicated_group_name_that_cannot_be_a_filename::">
      This example text should be in the second file
   </Item>
   <Item group="::this_long_and_complicated_group_name_that_cannot_be_a_filename::">
      Hello World!
   </Item>
</List>

如何编写转换(XSLT 2.0)以将这些转换输出到生成的文件名并且具有唯一值?例如:将第一个@group映射到file1.xml,将第二个@group映射到file2.xml

1 个答案:

答案 0 :(得分:3)

这是一个使用XSLT 2.0中一些优秀新功能的解决方案:

此转化

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
      <!--                                                  --> 
    <xsl:template match="/*">
      <xsl:variable name="vTop" select="."/>
      <!--                                                  --> 
        <xsl:for-each-group select="Item" group-by="@group">
          <xsl:result-document href="file:///C:/Temp/file{position()}.xml">
            <xsl:element name="{name($vTop)}">
              <xsl:copy-of select="current-group()"/>
            </xsl:element>
          </xsl:result-document>
        </xsl:for-each-group>
    </xsl:template>
</xsl:stylesheet>

应用于OP提供的Xml文档(更正为格式正确!):

<List>
    <Item group="::this_long_and_complicated_group_name_that_cannot_be_a_filename::">
         Hello World!
    </Item>
    <Item group="::this_other_long_and_complicated_group_name_that_cannot_be_a_filename::">
          Goodbye World!
  </Item>
    <Item group="::this_long_and_complicated_group_name_that_cannot_be_a_filename::">
          This example text should be in the first file
 </Item>
    <Item group="::this_other_long_and_complicated_group_name_that_cannot_be_a_filename::">
          This example text should be in the second file
 </Item>
    <Item group="::this_long_and_complicated_group_name_that_cannot_be_a_filename::">
          Hello World!
  </Item>
</List>

生成所需的两个文件 file1.xml和file2.xml