如何解决使用xsl从xml获取特定值
| 我有一个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>
解决方法
这是一个完整而又简短的转换:
<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>
,尝试这个:
<xsl:template match=\"attributes/attribute\">
<xsl:if test=\".//attributeName=\'salience\'\">
<xsl:value-of select=\".//value\"/>
</xsl:if>
</xsl:template>
附言由于XSL未显示,请格式化您的帖子。
,主要问题是此xsl:if语句
<xsl:if test=\"//attributes//attribute[(attributeName = \'salience\')]\">
此时,上下文仍然是根节点,因此,所有这些操作只是检查attibute元素的存在,您实际上并未将自己放置在该节点上。因此,当您执行xsl:value-of时,您只是在XML中获得第一个值。
而不是使用xsl:if,您应该尝试匹配attribute元素,如下所示
<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}\">
这样可以避免在匹配模板中对显着性进行硬编码,从而在您希望以类似方式匹配其他元素时使其更加通用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。