4

我有一长串带有命名标识符的 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

4

1 回答 1

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

于 2009-03-12T19:07:10.680 回答