2010-06-11 56 views
3

嗨有沒有人知道xsl看起來像轉換這個XML。 pid之後可以有N個nte,pv1之後可以有N個nte。結構是有保證的,所有遵循pid的nte都屬於pid,而pv1之後的所有nte都屬於pv1。創建從兄弟節點的子節點,直到發生不同的s 012

來源:

<pid> 
</pid> 
<nte> 
    <nte-1>1</nte-1> 
    <nte-3>Note 1</nte-1> 
</nte> 
<nte></nte> 
<pv1></pv1> 
<nte> 
</nte> 

到:

<pid> 
    <nte> 
    <nte-1>1</nte-1> 
    <nte-3>Note 1</nte-1> 
    </nte> 
    <nte> 
    </nte> 
</pid> 
<pv1> 
    <nte> 
    </nte> 
</pv1> 

謝謝!

+0

好問題(+1)。看到我的答案是一個簡短而有效的解決方案。 :) – 2010-06-11 21:46:58

回答

3

該轉化

<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="kLogicalChildren" match="nte" 
    use="generate-id(preceding-sibling::* 
         [self::pid or self::pv1] 
         [1])"/> 

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

<xsl:template match="pid|pv1"> 
    <xsl:copy> 
    <xsl:copy-of select="@*"/> 

    <xsl:copy-of select= 
    "key('kLogicalChildren', generate-id())"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="nte"/> 
</xsl:stylesheet> 

當所提供的XML文檔應用(校正爲良好的形成)

<t> 
    <pid></pid> 
    <nte> 
     <nte-1>1</nte-1> 
     <nte-3>Note 1</nte-3> 
    </nte> 
    <nte></nte> 
    <pv1></pv1> 
    <nte></nte> 
</t> 

產生想要的,正確的結果

<t> 
    <pid> 
     <nte> 
      <nte-1>1</nte-1> 
      <nte-3>Note 1</nte-3> 
     </nte> 
     <nte/> 
    </pid> 
    <pv1> 
     <nte/> 
    </pv1> 
</t> 
+0

工程就像一個魅力!謝謝! – user364939 2010-06-11 22:32:57

相關問題