2016-09-29 135 views
0

通用方式,我有這個以下XML結構:XSLT:以子節點移動到父節點在XML

<root> 
    <p1> 
    <a>1</a> 
    <b>2</b> 
    <_timestamp>20160928201109</_timestamp> 
    <c> 
    <_c_timestamp>20160928201056</_c_timestamp>Tmp</c> 
    </p1> 
    <p2> 
    <a>1</a> 
    <b>2</b> 
    <_timestamp>20160928201109</_timestamp> 
    <d> 
    <_d_timestamp>20160928201056</_d_timestamp>Tmp1</d> 
    </p2> 
</root> 

,並希望使用XSLT轉換成這種結構:

<root> 
    <p1> 
    <a>1</a> 
    <b>2</b> 
    <_timestamp>20160928201109</_timestamp> 
    <_c_timestamp>20160928201056</_c_timestamp> 
    <c>Tmp</c> 
    </p1> 
    <p2> 
    <a>1</a> 
    <b>2</b> 
    <_timestamp>20160928201109</_timestamp> 
    <_d_timestamp>20160928201056</_d_timestamp> 
    <d>Tmp1</d> 
    </p2> 
</root> 

即任何應該將結構爲<_anyName_timestamp>的標籤發生移動到父節點。

任何指向XSLT結構的指針都會有幫助。

+0

有沒有包含雙下劃線任何其他節點? –

+0

不,只有''_anyName_timestamp>''包含雙下劃線。 – Vinod

回答

1

任何出現結構爲<_anyName_timestamp>的標籤應該是 移動到父節點。

移動是這裏的一部分。困難的部分是確定要移動的元素。嘗試:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="*"> 
    <xsl:apply-templates select="*[starts-with(name(), '_') and contains(substring(name(), 2), '_timestamp')]"/> 
    <xsl:copy> 
     <xsl:apply-templates select="node()[not(starts-with(name(), '_') and contains(substring(name(), 2), '_timestamp'))]"/> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 

或許有點更優雅:

<xsl:template match="*"> 
    <xsl:variable name="ts" select="*[starts-with(name(), '_') and contains(substring(name(), 2), '_timestamp')]" /> 
    <xsl:apply-templates select="$ts"/> 
    <xsl:copy> 
     <xsl:apply-templates select="node()[count(.|$ts) > count($ts)]"/> 
    </xsl:copy> 
</xsl:template> 
+0

完美!解決方案按預期工作。 – Vinod