2012-09-09 32 views
1

我有XML文件和XSLT转换如下:如何从键选择哪些字段不为空

<?xml version="1.0" encoding="utf-8" ?> 
    <?xml-stylesheet version="1.0" type="text/xml" href="pets.xsl" ?> 
    <pets> 
     <pet name="Jace" type="dog" /> 
     <pet name="Babson" type="" /> 
     <pet name="Oakley" type="cat" /> 
     <pet name="Tabby" type="dog" /> 
    </pets> 

<?xml version="1.0" encoding="utf-8" ?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > 
    <xsl:key name="pets-key" match="pet" use="type" /> 
    <xsl:template match="/" > 
     <html> 
      <head><title></title></head> 
      <body> 
       <xsl:for-each select="key('pets-key', '')" > 
        <xsl:value-of select="@name" /> 
       </xsl:for-each> 
      </body> 
     </html> 
    </xsl:template> 
</xsl:stylesheet> 

如何选择使用密钥功能,所有类型的宠物不是空的?

回答

1

两点要注意:

  1. 。在你的键定义错误。您需要使用use =“@ type”,而不是use =“type”
  2. 您需要设置差异来选择所有类型为非空的宠物,并仍然使用key()函数。一般的配方在XPATH 1.0是一套区别...

    $节点设置1 [计数(|。$节点设置2)=计数($节点设置2)!]

把它总而言之,一个正确的,但inefficent XSLT 1.0样式表使用密钥()和列出所有的宠物不是空的类型是...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > 
<xsl:output method="html" indent="yes" /> 
<xsl:strip-space elements="*" /> 

<xsl:key name="kPets" match="pet" use="@type" /> 

<xsl:template match="/" > 
    <html> 
    <head><title>Pets with a type</title></head> 
    <body> 
     <ul> 
     <xsl:for-each select="*/pet[count(. | key('kPets', '')) != count(key('kPets', ''))]" > 
      <li><xsl:value-of select="@name" /></li> 
     </xsl:for-each> 
     </ul> 
    </body> 
    </html> 
</xsl:template> 

</xsl:stylesheet> 

这产生输出...

<html> 
    <head> 
    <META http-equiv="Content-Type" content="text/html; charset=utf-8"> 
    <title>Pets with a type</title> 
    </head> 
    <body> 
    <ul> 
     <li>Jace</li> 
     <li>Oakley</li> 
     <li>Tabby</li> 
    </ul> 
    </body> 
</html> 

话虽如此,这个问题并不适合作为使用密钥的好例子。在现实生活中,如果你想达到这个结果,一个更好,更高效的XSLT 1.0解决方案将是...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > 
<xsl:output method="html" indent="yes" /> 
<xsl:strip-space elements="*" /> 

<xsl:key name="kPets" match="pet" use="@type" /> 

<xsl:template match="/*" > 
    <html> 
    <head><title>Pets with a type</title></head> 
    <body> 
     <ul> 
     <xsl:apply-templates /> 
     </ul> 
    </body> 
    </html> 
</xsl:template> 

<xsl:template match="pet[@type != .]"> 
    <li><xsl:value-of select="@name" /></li> 
</xsl:template> 

</xsl:stylesheet> 
+0

你的解决方案非常详细,非常感谢 – testCoder