【问题标题】:XSLT for-each questionXSLT for-each question
【发布时间】:2010-09-02 00:34:25
【问题描述】:

我有一个 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?

【问题讨论】:

  • 好问题 (+1)。请参阅我的答案以获得简短而有效的解决方案。

标签: xml xslt xslt-2.0


【解决方案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>

【讨论】:

  • 谢谢。另外,如果 myChild 是 1BXY 怎么办? 如何通过 Child1 循环以使用上述 XSLT 变小。我很困惑为什么我会得到内部文本。
  • @Greens:我不明白——请描述得更好。您希望得到什么结果(请使用 XML)?
  • INPUT 1BXY ------------------------------------ 输出
  • 这与您在问题中提出的问题有很大不同。请根据您的新要求提出一个新问题。在发布新问题之前好好考虑一下,否则您可能会再次错过一些重要的事情。例如,在您想要的新输出中并不清楚anyName 的含义以及它与源 XML 的关系。
【解决方案2】:

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

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

<xsl:template match="Child2"/>

只要Child1 始终是Child2 的第一个后续兄弟,这将正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 2018-07-16
    相关资源
    最近更新 更多