2016-11-10 8 views
2

我需要知道給定的產品清單是否包含兩種特定的產品。如果兩者都存在,我需要忽略一個。如果只有其中一個存在,我需要保留該產品。如何檢查xml列表中的兩個代碼?

XML 1

<ns0:Items xmlns:ns0="abc"> 
    <ns0:Item> 
    <ns0:Code>X1</ns0:Code> <!-- keep this because it is the only one --> 
    <ns0:Quantity>1</ns0:Quantity> 
    </ns0:Item> 
</ns0:Items> 

XML 2

<ns0:Items xmlns:ns0="abc"> 
    <ns0:Item> 
    <ns0:Code>X1</ns0:Code> <!-- ignore this because we have another valid product --> 
    <ns0:Quantity>1</ns0:Quantity> 
    </ns0:Item> 
    <ns0:Item> 
    <ns0:Code>M1</ns0:Code> 
    <ns0:Quantity>1</ns0:Quantity> 
    </ns0:Item> 
</ns0:Items> 

XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns0="abc" version="1.0"> 
    <xsl:output method="xml" indent="yes" encoding="utf-16" omit-xml-declaration="no" /> 
    <xsl:template match="ns0:Items"> 
    <Items> 
     <xsl:variable name="hasBoth"> 
     <xsl:value-of select="boolean(ns0:Item/ns0:Code[.='M1']) and boolean(ns0:Item/ns0:Code[.='X1'])" /> 
     </xsl:variable> 
     <xsl:for-each select="ns0:Item"> 
     <xsl:variable name="validItem"> 
      <xsl:choose> 
      <xsl:when test="$hasBoth and ns0:Code='X1' and ns0:Quantity=1"> 
       <xsl:value-of select="0"/> 
      </xsl:when> 
      <xsl:otherwise> 
       <xsl:value-of select="1"/> 
      </xsl:otherwise> 
      </xsl:choose> 
     </xsl:variable> 
     <both> 
      <xsl:value-of select="$hasBoth"/> 
     </both> 
     <expr> 
      <xsl:value-of select="$hasBoth and ns0:Code='X1' and ns0:Quantity=1"/> 
     </expr> 
     <valid> 
      <xsl:value-of select="$validItem"/> 
     </valid> 
     <xsl:if test="$validItem = 1"> 
      <SalesOrderDetail> 
      <xsl:copy-of select="."/> 
      </SalesOrderDetail> 
     </xsl:if> 
     </xsl:for-each> 
    </Items> 
    </xsl:template> 
</xsl:stylesheet> 

結果1 - 這是錯誤的,它會刪除即使它是唯一一個在X1的產品, $ hasBoth怎麼可能是假的而且expr是真的?

<Items> 
    <both>false</both> 
    <expr>true</expr> 
    <valid>0</valid> 
</Items> 

結果2 - 正確的,它消除了X1產品

<Items> 
    <both>true</both> 
    <expr>true</expr> 
    <valid>0</valid> 
    <both>true</both> 
    <expr>false</expr> 
    <valid>1</valid> 
    <SalesOrderDetail> 
    </SalesOrderDetail> 
</Items> 
+0

你有兩個輸入和兩個結果,其中之一是不正確,如何正確的結果1應該是什麼? –

回答

1

我認爲這是你hasBoth變量的問題。當您創建它時使用xsl:value-of時,結果是一個字符串。

當您測試$hasBoth它是真實的,即使字符串值是「假」,因爲:

boolean("false") = true() 

而且,你不應該需要使用boolean()

嘗試修改此:

<xsl:variable name="hasBoth"> 
    <xsl:value-of select="boolean(ns0:Item/ns0:Code[.='M1']) and boolean(ns0:Item/ns0:Code[.='X1'])" /> 
</xsl:variable> 

這樣:

<xsl:variable name="hasBoth" 
     select="ns0:Item/ns0:Code[.='M1'] and ns0:Item/ns0:Code[.='X1']"/> 
+1

你會認爲有經驗的JavaScript會教會我確定我正確比較類型!謝謝。 – Nate