2011-08-01 38 views
0

我想问一下。有可能添加条件,这将检查XML数据与查找表,如果我们没有在查找表中的值添加常量8输出? XSLT代码:如何添加查询表检查xml数据的条件

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:key name="Department" match="Department" use="../Collection"/> 
    <xsl:template match="/"> 
    <document> 
     <xsl:apply-templates/> 
    </document> 
</xsl:template> 
<xsl:template match="line"> 
    <xsl:variable name="inputDep" select="field[@id='3']"/> 
<Department> 
    <xsl:for-each select="document('lookup.xml')"> 
     <xsl:for-each select="key('Deparment',$inputDep)"> 
      <xsl:value-of select="."/> 
     </xsl:for-each> 
    </xsl:for-each> 
</Department> 

</xsl:template> 

</xsl:stylesheet> 

查找表:

<document> 
    <line-item> 
     <Collection>1</Collection> 
     <Department>3</Department> 
    </line-item> 
    <line-item> 
     <Collection>2</Collection> 
     <Department>1</Department> 
    </line-item> 
    <line-item> 
     <Collection>3</Collection> 
     <Department>2</Department> 
    </line-item> 
</document> 

XML文件:

<document> 
    <line id="0"> 
     <field id="3"><![CDATA[1]]></field> 
    </line> 
    <line id="1"> 
     <field id="3"/> 
    </line> 
    <line id="2"> 
     <field id="3"/><![CDATA[4]]></field> 
    </line> 
</document> 

结果:

<Department>3<Department> 
<Department>8<Department> 
<Department>8<Department> 
+0

为什么内部for-each循环?你是否期望使用Deparment(sic)键的查找将返回多个节点?如果输出正确,输出是否正确? –

回答

1

你可以指定查找的值到变量并选择要执行的操作根据是否找到任何东西输出。

编辑2:完整演示样式表:

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

    <xsl:key name="Department" match="Department" use="../Collection"/> 

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

    <xsl:template match="line"> 
    <xsl:variable name="inputDep" select="field[@id='3']"/> 
    <Department> 
     <xsl:for-each select="document('lookup.xml')"> 
     <xsl:variable name="value" select="key('Department',$inputDep)"/> 
     <xsl:choose> 
      <xsl:when test="$value"> 
      <xsl:value-of select="$value"/> <!-- see note --> 
      </xsl:when> 
      <xsl:otherwise>8</xsl:otherwise> 
     </xsl:choose> 
     </xsl:for-each> 
    </Department> 
    </xsl:template> 

</xsl:stylesheet> 

注:替换原来的样式表xsl:for-each回路用一个简单的xsl:value-of,假设循环值不是故意的。如果真的是这样,你可以用for-each循环代替它。

+0

每个查找表的内部不用于xml文件。我尝试使用你的答案,但它不工作..我尝试添加你的代码,而不是每个循环。 – Petras

+0

@Petras,试图通过提供一个更完整的示例代码来说明我的想法,以阐明我的想法。 –

+0

我尝试了你的解决方案,首先在行显示错误。我尝试将选择值更改为/ field [@ id = 3],但后来所有部门= 8 – Petras