2010-01-22 73 views
3

我想測試一個標籤的存在並根據該結果創建新的節點..是否可以使用XSLT檢測(xml)標籤的存在?

這是輸入XML:

<root> 
    <tag1>NS</tag1> 
    <tag2 id="8">NS</tag2> 
    <test> 
    <other_tag>text</other_tag> 
    <main>Y</main> 
    </test> 
    <test> 
    <other_tag>text</other_tag> 
    </test> 
</root> 

而所需的輸出XML是:

<root> 
    <tag1>NS</tag1> 
    <tag2 id="8">NS</tag2> 
    <test> 
    <other_tag>text</other_tag> 
    <Main_Tag>Present</Main_Tag> 
    </test> 
    <test> 
    <other_tag>text</other_tag> 
    <Main_Tag>Absent</Main_Tag> 
    </test> 
</root> 

我知道測試標籤的價值,但這對我來說是新東西。

我試圖用這個模板: (不工作按要求)

<xsl:template match="test"> 
     <xsl:element name="test"> 
     <xsl:for-each select="/root/test/*"> 
     <xsl:choose> 
     <xsl:when test="name()='bbb'"> 
      <xsl:element name="Main_Tag"> 
      <xsl:text>Present</xsl:text> 
      </xsl:element> 
     </xsl:when> 
     <xsl:otherwise> 
      <xsl:element name="Main_Tag"> 
      <xsl:text>Absent</xsl:text> 
      </xsl:element> 
     </xsl:otherwise> 
     </xsl:choose> 
     </xsl:for-each> 
     </xsl:element> 
    </xsl:template> 

回答

1

我並不是說這是上級 - 對於這個問題,我可能會做完全相同的方式魯本斯法里亞斯介紹 - 但它表明解決這個問題的另一種方法在更復雜的情況下可能有用。我發現我推入模板匹配的邏輯越多,我的轉換就越具有靈活性和可擴展性,從長遠來看也是如此。因此,將這些添加到標識變換:

<xsl:template match="test/main"> 
    <Main_Tag>present</Main_Tag> 
</xsl:template> 

<xsl:template match="test[not(main)]"> 
    <xsl:copy> 
     <xsl:apply-templates select="node()|@*"/> 
     <Main_Tag>absent</Main_Tag> 
    </xsl:copy> 
</xsl:copy> 
5

什麼只是這樣的:

<xsl:choose> 
    <xsl:when test="main = 'Y'"> 
     <Main_Tag>Present</Main_Tag> 
    </xsl:when> 
    <xsl:otherwise> 
     <Main_Tag>Absent</Main_Tag> 
    </xsl:otherwise> 
</xsl:choose> 

或者

<Main_Tag> 
    <xsl:choose> 
     <xsl:when test="main = 'Y'">Present</xsl:when> 
     <xsl:otherwise>Absent</xsl:otherwise> 
    </xsl:choose> 
</Main_Tag> 
+0

謝謝先生..它完成.. :-) – 2010-01-22 10:40:31

+0

變體#2爲+1。更短,重複性更低。 – Tomalak 2010-01-22 11:07:07

+0

對不起,可能是迂腐,但你的代碼測試的主要元素的存在與值「Y」,不是嗎?當它具有另一個價值但仍然存在時會發生什麼? – 2010-01-22 12:28:15

1

你可以使用Xpath count function來查看main節點存在(count(name) = 0)並相應輸出。

1

擴大魯本斯法里亞斯第二個答案...

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <!--Identity transform--> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 

    <!--Add <Main_Tag>Present</Main_Tag> or <Main_Tag>Absent</Main_Tag>.--> 
    <xsl:template match="test"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
      <Main_Tag> 
       <xsl:choose> 
        <xsl:when test="main = 'Y'">Present</xsl:when> 
        <xsl:otherwise>Absent</xsl:otherwise> 
       </xsl:choose> 
      </Main_Tag> 
     </xsl:copy> 
    </xsl:template> 

    <!--Remove all <main> tags--> 
    <xsl:template match="main"/>  
</xsl:stylesheet>