如何使用XSL檢查值是空仍是空? node
例如,若是categoryName
爲空? 我在選擇構造時使用的是。 編程
例如: app
<xsl:choose> <xsl:when test="categoryName !=null"> <xsl:value-of select="categoryName " /> </xsl:when> <xsl:otherwise> <xsl:value-of select="other" /> </xsl:otherwise> </xsl:choose>
前兩個處理空值,第二個處理空字符串。 ide
<xsl:if test="USER/FIRSTNAME"> USERNAME is not null </xsl:if> <xsl:if test="not(USER/FIRSTNAME)"> USERNAME is null </xsl:if> <xsl:if test="USER/FIRSTNAME=''"> USERNAME is empty string </xsl:if> <xsl:if test="USER/FIRSTNAME!=''"> USERNAME is not empty string </xsl:if>
若是XML中可能存在該元素,我將測試元素是否存在以及字符串長度是否大於零: 函數
<xsl:choose> <xsl:when test="categoryName and string-length(categoryName) > 0"> <xsl:value-of select="categoryName " /> </xsl:when> <xsl:otherwise> <xsl:value-of select="other" /> </xsl:otherwise> </xsl:choose>
根據個人經驗,最好的方法是: 測試
<xsl:when test="not(string(categoryName))"> <xsl:value-of select="other" /> </xsl:when> <otherwise> <xsl:value-of select="categoryName" /> </otherwise>
我知道這個問題很老,但在全部答案之間,我想念一個在XSLT開發中這個用例的經常使用方法。 spa
我想象OP中缺乏的代碼看起來像這樣: code
<xsl:template match="category"> <xsl:choose> <xsl:when test="categoryName !=null"> <xsl:value-of select="categoryName " /> </xsl:when> <xsl:otherwise> <xsl:value-of select="other" /> </xsl:otherwise> </xsl:choose> </category>
而且輸入看起來像這樣: xml
<categories> <category> <categoryName>Books</categoryName> </category> <category> <categoryName>Magazines</categoryName> <categoryName>Periodicals</categoryName> <categoryName>Journals</categoryName> </category> <category> <categoryName><!-- please fill in category --></categoryName> </category> <category> <categoryName /> </category> <category /> </categories>
即,我假設能夠有零,空,單個或多個categoryName
元素。 使用xsl:choose
-style構造處理全部這些狀況,或者換句話說,命令性地,很快就會變得混亂(若是元素能夠處於不一樣的級別,則更是如此!)。 XSLT中的典型編程習慣是使用模板(所以是XSLT中的T),這是聲明性編程,而不是命令式的(您不告訴處理器該作什麼,只要知足某些條件就告訴您想要輸出什麼)。 對於此用例,可能以下所示: ip
<!-- positive test, any category with a valid categoryName --> <xsl:template match="category[categoryName[text()]]"> <xsl:apply-templates /> </xsl:template> <!-- any other category (without categoryName, "null", with comments etc) --> <xsl:template match="category"> <xsl:text>Category: Other</xsl:text> </xsl:template> <!-- matching the categoryName itself for easy handling of multiple names --> <xsl:template match="categoryName"> <xsl:text>Category: </xsl:text> <xsl:value-of select="." /> </xsl:template>
這適用於(使用任何XSLT版本),由於上面的第一個具備更高的優先級(它有一個謂詞)。 第二個「直通」匹配模板捕獲任何無效的匹配模板。 第三個而後負責以適當的方式輸出categoryName
值。
請注意,在這種狀況下,不須要特別匹配categories
或category
,由於處理器將自動處理全部子項,除非咱們另外說明(在此示例中,第二個和第三個模板不會進一步處理子項,由於有no xsl:apply-templates
in)。
這種方法比命令式方法更容易擴展,由於它自動處理多個類別,而且能夠經過添加另外一個匹配模板來擴展其餘元素或異常。 沒有if-branches的編程 。
注意:XML中沒有null
這樣的東西。 有xsi:nil ,但不多使用,特別是在沒有某種模式的無類型場景中不多使用。
若是節點在輸入xml中沒有可用的值,如xpath下面,
<node> <ErrorCode/> </node>
string()函數轉換爲空值。 因此這很好用:
string(/Node/ErrorCode) =''