如何检查xml列表中的两个代码?

问题描述:

我需要知道给定的产品清单是否包含两种特定的产品。如果两者都存在,我需要忽略一个。如果只有其中一个存在,我需要保留该产品。如何检查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应该是什么? –

我认为这是你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