XSLT 2.0:元素列表中是否存在值?

时间:2013-11-26 15:02:03

标签: xml xslt xslt-2.0

我有一个XML文档如下:

<Document>
  <Countries>
    <Country>Scotland</Country>
    <Country>England</Country>
    <Country>Wales</Country>
    <Country>Northern Ireland</Country>
  </Countries>

  <Populations>
    <Population country="Scotland" value="5" />
    <Population country="England" value="53" />
    <Population country="Wales" value="3" />
    <Population country="Northern Ireland" value="2" />
    <Population country="France" value="65" />
    <Population country="" value="35" />
  </Populations>
</Document>

我正在尝试编写一个XSLT语句,该语句将访问其“country”属性为空或其“country”属性不在/ Document / Countries / Country

中的所有Population元素

我的XSLT如下所示:

<xsl:variable name="countries" select="/Document/Countries/Country" />
<xsl:variable name="populations" select="/Document/Populations/Population" />

<xsl:variable name="populationsNotInList" select="$populations[(@country = '') OR (@country NOT IN $countries)" />

你能帮我填写$ populationNotInList变量的'NOT IN $ countries'吗?

我基本上是在寻找输出:

<Population country="France" value="65" />
<Population country="" value="35" />

2 个答案:

答案 0 :(得分:2)

使用<xsl:variable name="populationsNotInList" select="$populations[(@country = '') or not(@country = $countries)" />或更好地定义密钥

<xsl:key name="country" match="Countries/Country" use="."/>

然后你可以<xsl:variable name="populationsNotInList" select="$populations[(@country = '') or not(key('country', @country))" />

答案 1 :(得分:1)

如果您不一定需要将它们存储在变量中,那么就可以访问相关节点。

<?xml version="1.0" encoding="utf-8"?>

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

<xsl:output method="xml" indent="yes"/>

<xsl:strip-space elements="*"/>

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

<xsl:template match="Document">
   <xsl:for-each select="Populations/Population">
     <xsl:if test="@country = '' or not(../../Countries/Country[.=current()/@country])">
        <xsl:copy>
           <xsl:copy-of select="@*"/>
        </xsl:copy>
     </xsl:if>
   </xsl:for-each>
</xsl:template>

<xsl:template match="Country"/>

</xsl:stylesheet>

这为您提供了以下输出(假设输入正确 - 您的输入XML不正确):

<?xml version="1.0" encoding="UTF-8"?>

<Population country="France" value="65"/>
<Population country="" value="35"/>