2010-01-22 57 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> 
相关问题