2012-12-05 64 views
0

我一直在嘗試使用XSLT實現以下輸出,但實際上一直在掙扎。提前感謝您的幫助。如果存在子節點,則創建新的XML節點

<par> 
    <run>Line one<break/> 
     Line two<break/> 
    </run> 

    <run>Another para of text<break/> 
    </run> 

    <run>3rd para but no break</run>  
</par> 

<document> 
    <para>Line one</para> 
    <para>Line two</para> 
    <para>Another para of text</para> 
    <para>3rd para but no break</para> 
</document> 

謝謝

DONO

+0

Pl緩解包括一些代碼來顯示 [你試過](http://whathaveyoutried.com) –

回答

2

這裏有一個簡單的解決方案,是推動爲主導,並不需要<xsl:for-each><xsl:if>,或self::軸。

當這個XSLT:

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

    <xsl:template match="/*"> 
    <document> 
     <xsl:apply-templates /> 
    </document> 
    </xsl:template> 

    <xsl:template match="run/text()"> 
    <para> 
     <xsl:value-of select="normalize-space()" /> 
    </para> 
    </xsl:template> 

</xsl:stylesheet> 

......被應用於提供的XML:

<par> 
    <run>Line one<break/> 
     Line two<break/> 
    </run> 

    <run>Another para of text<break/> 
    </run> 

    <run>3rd para but no break</run>  
</par> 

......想要的結果產生:

<document> 
    <para>Line one</para> 
    <para>Line two</para> 
    <para>Another para of text</para> 
    <para>3rd para but no break</para> 
</document> 
0

假設你<run>元素永遠只能將包含文本和<break/>元素和你想規範化空白並排除<para>元素將只包含空格(按所需輸出建議),下面應該工作:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:output indent="yes"/> 

    <xsl:template match="par"> 
     <document> 
      <xsl:apply-templates select="*"/> 
     </document> 
    </xsl:template> 

    <xsl:template match="run"> 
     <xsl:for-each select="text()"> 
      <xsl:if test="normalize-space(self::text()) != ''"> 
       <para> 
        <xsl:value-of select="normalize-space(self::text())"/> 
       </para> 
      </xsl:if> 
     </xsl:for-each> 
    </xsl:template> 

</xsl:stylesheet> 
+0

忘記XML遊樂場鏈接:[鏈接](http://www.xmlplayground.com/rFodnR) –