2011-05-20 119 views
1

我在某些xml上運行xsl轉換,並且需要能夠在幾個標籤上設置一些默認值(如果它們顯示爲空)。例如,我的XML已經XSLT在空xml標籤中設置默認值

<record> 
<name>Bob</name> 
<latitude>51.23645</latitude> 
<longitude>-0.1254</longitude> 
<rank></rank> 
</record> 

<record> 
<name>Chantel</name> 
<latitude></latitude> 
<longitude></longitude> 
<rank>5</rank> 
</record> 

,我想一些默認設置爲輸出:

<record> 
<name>Bob</name> 
<latitude>51.23645</latitude> 
<longitude>-0.1254</longitude> 
<rank>0</rank> 
</record> 

<record> 
<name>Chantel</name> 
<latitude>0.00</latitude> 
<longitude>0.00</longitude> 
<rank>5</rank> 
</record> 

我想這將是簡單的,但似乎無法破解它。

在此先感謝。

編輯:這就是我想要做的。仍然只是在黑暗中摸索摸索!

<xsl:template match="record"> 
    <xsl:when test="name()='latitude'"> 
    <xsl:element name="latitude"> 
     <xsl:choose> 
     <xsl:when test="text()=''"> 
      <latitude>0.00</latitude> 
     </xsl:when> 
     <xsl:otherwise> 
      <xsl:value-of select="latitude"></xsl:value-of> 
     </xsl:otherwise> 
     </xsl:choose> 
    </xsl:element> 
    </xsl:when> 
</xsl:template> 
+0

你能展示你的XSL'過渡'嗎?你在使用參數嗎? – 2011-05-20 14:49:09

+0

@empo我剛剛編輯我的帖子,以顯示我的(可憐的)嘗試寫這個過渡... – Willb 2011-05-20 15:48:42

回答

3

試試這個:

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

    <xsl:output method="xml" indent="yes"/> 
    <xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
    </xsl:template> 
    <xsl:template match="rank[not(text())]"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*"/> 
     <xsl:text>0</xsl:text> 
    </xsl:copy> 
    </xsl:template> 
    <xsl:template match="latitude[not(text())]|longitude[not(text())]"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*"/> 
     <xsl:text>0.00</xsl:text> 
    </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 

添加更多的模板爲其他標籤設置默認值。

工作原理:第一個模板被稱爲「身份模板」,並將輸入到輸出的節點複製爲未改變。第二個模板匹配沒有文本子節點(即空的「等級」節點)的「等級」節點,將它們複製到具有其屬性的輸出中,然後插入默認值。

+0

謝謝,但我無法得到這個工作。只處理已有值的標籤。空xml標籤不輸出。 – Willb 2011-05-20 15:54:36

+0

這適用於我使用Oxygen/XML的XSLT處理器(Saxon)。你在使用哪種XSLT處理器?您是否添加了模板,使用我的回覆中第二個模板的模式,針對您要爲其設置默認值的所有不同標籤? – 2011-05-20 16:01:09

+0

謝謝吉姆。我正在使用MS Access作爲處理器。我有很多標籤需要默認(以上只是一個演示),所以在單個標籤上進行測試 - 這會有所作爲嗎? – Willb 2011-05-20 16:06:55