2016-06-21 67 views
1

所以我的問題是這樣的。我有一個在許多地方使用的變換文檔,通常處理很多小格式變換。在一個特定情況下,我需要從結果中刪除空格。輸出看起來是這樣的:XSLT:刪除多餘的空白字符保留節點

「\ n                   <我>的東西</I>非常顯着的有上標註< SUP> 1 </SUP> \ n            '

我已經試過上的變化:

<xsl:template match="no_whitespace"> 
    <xsl:variable name="result"> 
     <xsl:apply-templates/> 
    </xsl:variable> 
    <xsl:copy-of select="normalize-space($result)"/> 
</xsl:template> 

但子節點從輸出中剝離。我必須非常小心,不要設置像'text()'這樣的通用模板,因爲它會干擾變換的一般處理。似乎我在這裏錯過了一些明顯的東西。

編輯:試圖寫作由Stefan Hegny建議的身份轉換。

<xsl:template match="title_full"> 
    <xsl:apply-templates mode="stripwhitespace"/> 
</xsl:template> 

<xsl:template match="text()" mode="stripwhitespace"> 
    <xsl:value-of select="normalize-space(translate(., '\n', ''))"/> 
</xsl:template> 

<xsl:template match="/ | @* | *" mode="stripwhitespace"> 
    <xsl:apply-templates select="."/> 
</xsl:template> 

這解決了我的問題,即在標記的最高級別刪除空格和換行符,然後允許轉換正常進行。對於這個虛構的問題抱歉,並感謝您的幫助。

編輯第二:'translate'的使用不像我預期的那樣工作,它按字符工作。我使用了一種替換子字符串的轉換。

+0

請給XML輸入的reprsentative例子。 –

+0

\ n 東西喜歡帶腳註的標題腳註這是腳註,其他轉換大部分都會被刪除。我們已經完成\ n Snow

+0

我應該補充說,這個例子是我正在使用的標題xml的一個例子,但是轉換也能夠接收各種大段的文本,包含多個段落, – Snow

回答

0

我有兩個選擇:

如果\ n它不是字面那麼這樣做:

<xsl:template match="text()[ancestor-or-self::no_whitespace]"> 
    <xsl:value-of select="normalize-space(.)"/> 
</xsl:template> 

清理no_whitespace標記處和下方的所有空白處。

如果\ n是字符串中的文字,那麼它會變得更復雜以擺脫\ n。使用此:

<xsl:template name="strip_newline"> 
    <xsl:param name="string"/> 
    <xsl:value-of select="substring-before($string,'\n')"/> 
    <xsl:variable name="rhs" select="substring-after($string,'\n')"/> 
    <xsl:if test="$rhs"> 
     <xsl:call-template name="strip_newline"> 
      <xsl:with-param name="string" select="$rhs"/> 
     </xsl:call-template> 
    </xsl:if> 
</xsl:template> 

<xsl:template match="text()[ancestor-or-self::no_whitespace]"> 
    <xsl:value-of select="normalize-space(.)"/> 
</xsl:template> 

<xsl:template match="text()[ancestor-or-self::no_whitespace][contains(.,'\n')]"> 
    <xsl:variable name="cleantext"> 
     <xsl:call-template name="strip_newline"> 
      <xsl:with-param name="string" select="."/> 
     </xsl:call-template> 
    </xsl:variable> 
    <xsl:value-of select="normalize-space($cleantext)"/> 
</xsl:template> 

在這兩種情況下,我假設你已經在你的xsl有到位的身份模板別處:

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

當您使用normalize-space時,只使用片段的文本值,因此子節點被剝離。你必須把normalize-space成子節點,以及模板(那些由你<xsl:apply-templates/>

+0

不幸的是,我不能把標準化空間放到其他模板中,因爲它們也處理具有線返回的文本,並且適當地如此。 – Snow

+0

但是你會在你顯示的代碼中刪除這些換行符......?否則,你必須做一個略微修改的身份轉換,指定一個「mode =」removewhite「(例如),並在裏面做'text()'的標準化空間(搜索標識轉換xslt,如果你有困難回來;-) –

+0

標記這是答案,因爲解決方案來自對它的評論。 – Snow

0

它cound只是在輸出縮進應用於你有< XSL:輸出縮進=「是」/>在你的頂部xsl?或者,也許處理器正在執行縮進。使用< xsl:output indent =「no」/>應該吸收所有的\ n和縮進。

+0

換行符和額外間距直接來自輸入數據。這是一個數據問題,其中一些Marklogic數據庫條目在標籤內存在應該不存在的換行符。 – Snow