【问题标题】:xslt 1.0 - transform nodes before specific element into other elementxslt 1.0 - 将特定元素之前的节点转换为其他元素
【发布时间】:2011-01-10 17:51:01
【问题描述】:

我有以下输入:

<p>
    XYZZ
    <nl/>
    DEF
    <process>gggg</process>
    KKK
    <nl/>
    JKLK
    <nl/>
    QQQQ
</p>

我需要由元素&lt;nl/&gt; 分隔的每个节点在元素&lt;title&gt; 中输出:

<p>      
    <title>XYZZ</title>  
    <title>
        DEF<process>gggg</process>KKK  
    </title>  
    <title>JKLK</title>  
    <title>QQQQ</title>  
</p>

` 请建议我获得指定输出的方法。

【问题讨论】:

  • 好问题,+1。请参阅我的答案以获取最有效的完整且简短的解决方案。我已经仔细解释了这个解决方案中的所有步骤:)

标签: xslt xslt-1.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="kFollowing" match="/*/node()[not(self::nl)]"
  use="generate-id(preceding-sibling::nl[1])"/>

 <xsl:key  name="kPreceding" match="/*/node()[not(self::nl)]"
  use="generate-id(following-sibling::nl[1])"/>

    <xsl:template match="node()|@*">
      <xsl:copy>
         <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>

    <xsl:template match="/*">
     <xsl:copy>
      <xsl:apply-templates select="@*|nl"/>
     </xsl:copy>
    </xsl:template>

    <xsl:template match="nl" name="groupFollowing">
      <title>
       <xsl:apply-templates select="key('kFollowing',generate-id())"/>
      </title>
    </xsl:template>

    <xsl:template match="nl[1]">
     <title>
       <xsl:apply-templates select="key('kPreceding',generate-id())"/>
     </title>
     <xsl:call-template name="groupFollowing"/>
    </xsl:template>
</xsl:stylesheet>

应用于提供的 XML 文档时

<p>
       XYZZ
       <nl/>
       DEF
       <process> gggg </process>
       KKK
       <nl/>
       JKLK
       <nl/>
       QQQQ
</p>

产生想要的正确结果

<p>
   <title>
       XYZZ
       </title>
   <title>
       DEF
       <process> gggg </process>
       KKK
       </title>
   <title>
       JKLK
       </title>
   <title>
       QQQQ
</title>
</p>

请注意

  1. 使用身份规则“按原样”复制节点。

  2. 有特定的模板匹配顶部元素,顶部元素的第一个 nl 子元素和顶部元素的任何 nl 子元素。

  3. 定义了两个键,用于选择紧接在 nl 元素之前的所有非nl 节点和紧随 nl 元素之后的所有节点。 p>

  4. nl 元素被title 元素替换,所有紧随其后的非nl 节点都被处理,结果被放入这个title 元素.

  5. 对于第一个(其父级的子级)nl 元素,有一个初始步骤,其中添加了一个title 元素,并且所有紧接在其前面的非nl处理节点并将结果放入此title 元素。然后进行上述步骤4.中的处理。

【讨论】:

  • 非常感谢,Dimitre.. :) 对我来说效果很好。它也让我清除了使用密钥,生成 ID 功能的概念。 :-)
  • +1 好答案。您还可以为第一组使用一个键和一个空键值。但这更清楚,真的。
猜你喜欢
  • 1970-01-01
  • 2012-11-01
  • 2021-02-02
  • 1970-01-01
  • 2011-10-27
  • 1970-01-01
  • 2015-07-16
  • 2018-10-25
  • 1970-01-01
相关资源
最近更新 更多