使用XSLT解析多个属性值并将它们交错输出

时间:2014-11-07 15:40:58

标签: xml xslt

我需要改变这样的事情:

<IndexField NAME="Field1" VALUE="1;2;3" />
<IndexField NAME="Field2" VALUE="4;5;6" />
<IndexField NAME="Field3" VALUE="7;8;9" />

这样的事情:

<Document>
    <Field1>1</Field1>
    <Field2>4</Field2>
    <Field3>7</Field3>
</Document>
<Document>
    <Field1>2</Field1>
    <Field2>5</Field2>
    <Field3>8</Field3>
</Document>
<Document>
    <Field1>3</Field1>
    <Field2>6</Field2>
    <Field3>9</Field3>
</Document>

这篇文章(Using XSLT 2.0 to parse the values of multiple attributes into an array-like structure)很有帮助,但并没有让我一路走来,因为交错输出会使这更加复杂。

提前致谢!

1 个答案:

答案 0 :(得分:0)

使用XSLT 2.0,使用样式表

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output indent="yes"/>

<xsl:template match="Root">
  <xsl:variable name="IndexFields" select="IndexField"/>
  <xsl:variable name="Fields">
    <xsl:apply-templates select="$IndexFields"/>
  </xsl:variable>
  <xsl:for-each-group select="$Fields/*" group-by="(position() - 1) mod count($IndexFields)">
    <Document>
      <xsl:copy-of select="current-group()"/>
    </Document>
  </xsl:for-each-group>
</xsl:template>

<xsl:template match="IndexField">
  <xsl:variable name="this" select="."/>
  <xsl:for-each select="tokenize(@VALUE, ';')">
    <xsl:element name="{$this/@NAME}">
      <xsl:value-of select="."/>
    </xsl:element>
  </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

输入样本

<Root>
<IndexField NAME="Field1" VALUE="1;2;3" />
<IndexField NAME="Field2" VALUE="4;5;6" />
<IndexField NAME="Field3" VALUE="7;8;9" />
</Root>

转化为

<Document>
   <Field1>1</Field1>
   <Field2>4</Field2>
   <Field3>7</Field3>
</Document>
<Document>
   <Field1>2</Field1>
   <Field2>5</Field2>
   <Field3>8</Field3>
</Document>
<Document>
   <Field1>3</Field1>
   <Field2>6</Field2>
   <Field3>9</Field3>
</Document>