1

我有一个xml

<Root>
  <Parent>
    <Child1>A</Child1>
    <Child2>B</Child2>
    <Child1>X</Child1>
    <Child2>Y</Child2>
  </Parent>
</Root>

Child2 总是和 child1 在一起。我需要知道如何循环使用xsl:foreach和创建 XML 输出示例。

<TransformedXML>
  <Child attribute1="A" attribute2="B"/>
  <Child attribute1="X" attribute2="Y"/>
</TransformedXML>

我的问题是如何在 XSLT 中循环考虑 Child2 节点将始终跟随 Child1?

4

2 回答 2

1

这种转变

<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:key name="kFollowingChild1" match="*[not(self::Child1)]"
  use="generate-id(preceding-sibling::Child1[1])"/>

 <xsl:template match="Parent">
  <TransformedXML>
   <xsl:apply-templates/>
  </TransformedXML>
 </xsl:template>

 <xsl:template match="Child1">
  <Child>
   <xsl:for-each select=".|key('kFollowingChild1', generate-id())">
    <xsl:attribute name="attribute{position()}">
      <xsl:value-of select="."/>
    </xsl:attribute>
   </xsl:for-each>
  </Child>
 </xsl:template>

 <xsl:template match="text()"/>
</xsl:stylesheet>

当应用于提供的(多次更正以形成良好格式!) XML 文档时

<Root>
    <Parent>
        <Child1>A</Child1>
        <Child2>B</Child2>
        <Child1>X</Child1>
        <Child2>Y</Child2>
    </Parent>
</Root>

产生想要的正确结果

<TransformedXML>
   <Child attribute1="A" attribute2="B"/>
   <Child attribute1="X" attribute2="Y"/>
</TransformedXML>
于 2010-09-02T00:51:47.273 回答
0

是否有您不想使用的特定原因xsl:for-each?我建议只使用匹配的模板:

<xsl:template match="Child1">
  <Child attribute1="{.}" attribute2="{following-sibling::*[1]}"/>
</xsl:template>

<xsl:template match="Child2"/>

只要先决条件Child1始终是Child2.

于 2010-09-02T08:45:21.687 回答