簡體   English   中英

XSLT每個問題

[英]XSLT for-each question

我有一個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>

我的問題是,考慮到Child2節點始終跟隨Child1,我如何在XSLT中循環?

此轉換

<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>

您是否不使用xsl:for-each原因是否具體? 我建議只使用匹配的模板:

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

<xsl:template match="Child2"/>

就好,只要這將工作為前提Child1始終將先上后下的兄弟姐妹Child2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM