使用xsl从xml获取特定值

时间:2011-05-24 03:19:58

标签: xslt

我有一个xml如下。

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
  <h2>My CD Collection</h2>
  <table border="1">
    <tr bgcolor="#9acd32">
      <th>Title</th>
      <th>Artist</th>
    </tr>
    <xsl:for-each select="catalog/cd">
    <tr>
      <td><xsl:value-of select="title"/></td>
      <td><xsl:value-of select="artist"/></td>
    </tr>
    </xsl:for-each>
  </table>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet> 

3 个答案:

答案 0 :(得分:1)

这是一个完整而又简短的转型:

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

 <xsl:template match="attributeName[.='salience']">
  <salience>
   <xsl:value-of select="../value"/>
  </salience>
 </xsl:template>
 <xsl:template match="text()"/>
</xsl:stylesheet>

并应用于提供的XML文档

<attributes>
    <attribute>
        <attributeName>agenda-group</attributeName>
        <value>common</value>
    </attribute>
    <attribute>
        <attributeName>auto-focus</attributeName>
        <value>true</value>
    </attribute>
    <attribute>
        <attributeName>no-loop</attributeName>
        <value>true</value>
    </attribute>
    <attribute>
        <attributeName>salience</attributeName>
        <value>73</value>
    </attribute>
</attributes>

产生了想要的正确结果

<salience>73</salience>

答案 1 :(得分:0)

试试这个:

  <xsl:template match="attributes/attribute">
    <xsl:if test=".//attributeName='salience'">
      <xsl:value-of select=".//value"/>
    </xsl:if>
  </xsl:template>

P.S。请格式化您的帖子,因为XSL没有显示。

答案 2 :(得分:0)

主要问题是 xsl:if 声明

<xsl:if test="//attributes//attribute[(attributeName = 'salience')]">

此时,上下文仍然是根节点,所以这一切都是检查现有的 attibute 元素,实际上并没有将自己定位在节点上。因此,当您执行 xsl:value-of 时,您只需在XML中获得第一个

您应该尝试匹配属性元素,而不是使用 xsl:if ,而不是

<xsl:apply-templates select="attributes/attribute[attributeName = 'salience']"/>

整个XSLT如下

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="/">
      <xsl:apply-templates select="attributes/attribute[attributeName = 'salience']"/>
   </xsl:template>
   <xsl:template match="attribute">
      <xsl:element name="{attributeName}">
         <xsl:value-of select="value"/>
      </xsl:element>
   </xsl:template>
</xsl:stylesheet>

在输入XML上应用时,输出如下:

<salience>73</salience>

请注意 xsl:element

的使用
<xsl:element name="{attributeName}">

这样可以避免在匹配模板中对显着性进行硬编码,如果您希望以类似的方式匹配其他元素,则会更加通用。

相关问题