2010-09-02 51 views
1

我有一個XMLXSLT的,每個問題

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

+0

好問題(+1)。看到我的答案是一個簡短而有效的解決方案。 – 2010-09-02 00:52:23

回答

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

謝謝。此外,如果myChild是什麼 X Ÿ 我怎樣才能環路直通的child1得到小與上述XSLT。我很困惑,爲什麼我得到內在的文本。 – Greens 2010-09-02 02:33:39

+0

@綠色:我不明白 - 請描述得更好。你想得到什麼結果(XML,請)? – 2010-09-02 02:45:20

+0

INPUT Xý ---------------------------- -------- OUTPUT Greens 2010-09-02 02:51:08

0

爲什麼你不想使用xsl:for-each是否有特定的原因?我建議只使用匹配模板:

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

<xsl:template match="Child2"/> 

這會就好了工作,只要前提是Child1始終將Child2先上後下的兄弟姐妹。