2016-06-18 23 views
2

我創建了一個包含各種驗證等的XSLT。現在,我的客戶希望我爲每個空值傳遞XXX。有很多領域,我不想爲每個領域手動做。可以請你幫忙。下面是我的XSLT使用XSLT爲每個空字段傳遞文本值

(編輯並簡化我查詢)

我的XML:

<?xml version="1.0" encoding="UTF-8"?> 
<contract> 
<customerName>foo</customerName> 
<contractID /> 
<customerID>912</customerID> 
<countryCode/> 
<cityCode>7823</cityCode> 
</contract> 

XSLT:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 

<xsl:template match="/"> 
    <xsl:value-of select="contract/customerName"/> 
    <xsl:text>|</xsl:text> 
    <xsl:value-of select="contract/contractID"/> 
</xsl:template> 

</xsl:stylesheet> 

我想要的輸出爲Foo | XXX(XXX爲任何空白字段)

+0

如果沒有輸入XML的樣本顯示這些「空白值」中的一部分,它將很難爲您提供幫助。 –

+0

我已經用XML更新了。謝謝 – Sunny

+0

以下是一個關鍵問題:所有必填字段是否始終存在(即使空),還是可能完全缺失)? - P.S.如果可以將示例減少到重現問題所需的最小值,那將是非常好的,請參閱:[mcve] –

回答

1

既然你似乎在使用XSLT 2.0,我會建議一種截然不同的方法。

這裏有一個最小化的例子,產生的結果的標題部分:

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:wd="urn:com.workday/bsvc"> 
<xsl:output method="text"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="wd:Get_Workers_Response"> 
    <!--Defining Header--> 
    <xsl:variable name="header-fields" select=" 
     wd:Request_Criteria/wd:Organization_Reference/wd:ID[@wd:type='Organization_Reference_ID'], 
     wd:Response_Results/wd:Total_Results, 
     wd:Response_Results/wd:Total_Pages, 
     format-date(current-date(), '[M01][D01][Y0001]')" /> 
    <xsl:value-of select="string-join(for $i in $header-fields return if (string($i)) then $i else 'XXX', '|')"/> 
    <xsl:text>&#xa;</xsl:text> 
    <!--Ending Header--> 

    <!-- ... continue for Employee Data and Footer ... --> 
</xsl:template> 

</xsl:stylesheet> 

注意,這個假設一個「場」可以爲空,但不缺。

+0

謝謝邁克爾,我能夠使用此代碼。謝謝你的幫助 – Sunny

2

使用此模板:

<xsl:template match="*[normalize-space(text()) = '']"> 
    <xsl:copy>XXX</xsl:copy> 
</xsl:template> 
+0

我加了這個,但沒有工作。我是否正確地放置代碼? – Sunny

0

從@Kirill舒克答案繼,

使用:

<!-- the not(*) is optional in the case, but ensure you're only hitting on leaf nodes --> 
<xsl:template match="*[not(*) and normalize-space(text()) = '']"> 
    <xsl:text>XXX</xsl:text> 
</xsl:template> 

和更改所有<的xsl:value-of的... /><的xsl:適用─模板... /> 默認的xsl模板規則應該選取包含文本的節點並按正常方式輸出值。

相關問題