2013-07-04 74 views
0

我正在將一個XML文件轉換爲另一種XML格式。檢查節點是否存在於具有XSLT的文檔中

下面是示例源文件:

<xml> 
    <title>Pride and Prejudice</title> 
    <subtitle>Love Novel</subtitle> 
</xml> 

這裏是XSL文件:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<xsl:stylesheet version="1.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

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

<xsl:template match="title"> 
    <TitleDetail> 
     <TitleType>01</TitleType> 
     <TitleElement> 
      <TitleElementLevel>01</TitleElementLevel> 
      <TitleText><xsl:value-of select="current()"/></TitleText> 
      <!--Here Problem!!!--> 
      <xsl:if test="subtitle"> 
       <Subtitle>123</Subtitle> 
      </xsl:if> 
     </TitleElement> 
    </TitleDetail> 
</xsl:template> 

想法是,如果源文件包含字幕標記我需要插入 「字幕」節點到「TitleDetail」,但是「if」條件返回false。如何檢查源文件是否有字幕信息?

回答

1

我會定義另一個模板

<xsl:template match="subtitle"> 
    <Subtitle><xsl:value-of select="."/></Subtitle> 
</xsl:template> 

然後在主title模板應用模板../subtitle(即從瀏覽title元素對應subtitle

<TitleText><xsl:value-of select="."/></TitleText> 
<xsl:apply-templates select="../subtitle" /> 

您不需要if測試,因爲apply-templates將不會執行任何操作,前提是select找不到任何匹配的節點。

您還需要排除subtitle元素應用模板到xml元素的孩子時,否則你將TitleDetail以及它裏面的一個後得到Subtitle輸出元素的第二個副本。最簡單的方法是用下面的match="/*"一個替代

<xsl:template match="/*"> 
    <Product> 
     <xsl:apply-templates select="*[not(self::subtitle)]/> 
    </Product> 
</xsl:template> 

,以取代match="/"模板如果您有其他模板其他元素,你可以添加這些到not(),即select="*[not(self::subtitle | self::somethingelse)]"類似的特殊處理。

另外,您可以利用模板模式

<?xml version="1.0" encoding="ISO-8859-1"?> 
<xsl:stylesheet version="1.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

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

<xsl:template match="title"> 
    <TitleDetail> 
     <TitleType>01</TitleType> 
     <TitleElement> 
      <TitleElementLevel>01</TitleElementLevel> 
      <TitleText><xsl:value-of select="."/></TitleText> 
      <xsl:apply-templates select="../subtitle" mode="in-title" /> 
     </TitleElement> 
    </TitleDetail> 
</xsl:template> 

<!-- in "in-title" mode, add a Subtitle element --> 
<xsl:template match="subtitle" mode="in-title"> 
    <Subtitle><xsl:value-of select="."/></Subtitle> 
</xsl:template> 

<!-- in normal mode, do nothing --> 
<xsl:template match="subtitle" /> 
+0

感謝您的幫助。我嘗試了你的解決方案,但字幕標籤已被替換兩次:一個'Subtitle'是'TitleDetail'的後代,另一個是'Product'元素的後代。 「TitleDetail」中只需要一個'Subtitle'標籤。附: - 我使用這一行。 – Tamara

+0

@Tamara我已經添加了一些可能的方法來解決這個問題。 –

+0

謝謝,它的工作原理。 – Tamara

0

如果我理解正確的問題,你可以試試這個:

<xsl:if test="following-sibling::subtitle"> 
    <Subtitle>123</Subtitle> 
</xsl:if> 
+0

感謝您的幫助。我忘了提及這個字幕不一定是在兄弟姐妹之後 - 這只是兄弟姐妹。 – Tamara

相關問題