如何使用XSLT动态比较Book/author_name与author_details/author_name?
当然可以实现!
完全没问题,XSLT天生就适合处理这种XML节点间的内容匹配与比较。我给你一个具体的实现方案,包含示例XML和对应的XSLT代码,你可以直接参考:
第一步:准备带测试数据的XML
先给你提供一份填充了示例内容的XML(基于你给出的结构),这样能更直观看到效果:
<root> <Book> <Book_title>XSLT入门指南</Book_title> <author_name>张三</author_name> </Book> <Book> <Book_title>XML高级应用</Book_title> <author_name>李四</author_name> </Book> <author_details> <author_name>张三</author_name> <author_DOB>1980-01-01</author_DOB> </author_details> <author_details> <author_name>王五</author_name> <author_DOB>1985-05-05</author_DOB> </author_details> </root>
第二步:编写XSLT实现动态比较
下面的XSLT会遍历每本图书,自动匹配对应的作者详情,本质就是动态比较Book/author_name和author_details/author_name的内容:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 定义索引键,用作者名快速定位详情节点,大数据量下更高效 --> <xsl:key name="author-by-name" match="author_details" use="author_name"/> <xsl:template match="/root"> <html> <body> <h2>书籍作者匹配结果</h2> <ul> <!-- 遍历所有书籍节点 --> <xsl:for-each select="Book"> <li> <xsl:value-of select="Book_title"/> - 作者:<xsl:value-of select="author_name"/> <!-- 保存当前书籍的作者名,方便后续比较 --> <xsl:variable name="current-author" select="author_name"/> <!-- 判断是否存在匹配的作者详情 --> <xsl:choose> <xsl:when test="key('author-by-name', $current-author)"> <xsl:text> | 找到作者详情:出生日期 </xsl:text> <xsl:value-of select="key('author-by-name', $current-author)/author_DOB"/> </xsl:when> <xsl:otherwise> <xsl:text> | 未找到该作者的详细信息</xsl:text> </xsl:otherwise> </xsl:choose> </li> </xsl:for-each> </ul> </body> </html> </xsl:template> </xsl:stylesheet>
关键逻辑说明
- 索引优化:用
<xsl:key>创建作者名到详情节点的映射,比直接遍历查找效率高很多,适合数据量大的场景。 - 动态比较:
key('author-by-name', $current-author)本质就是在匹配author_details/author_name等于当前书籍作者名的节点,这就是动态比较的核心。 - 结果输出:通过
<xsl:choose>分支判断比较结果,输出对应的提示或详情。
如果你的XML结构更复杂,或者需要更复杂的比较逻辑(比如模糊匹配),也可以基于这个思路调整,比如用contains()函数替代直接相等判断。
内容的提问来源于stack exchange,提问作者Floki
相关产品推荐
相关产品推荐

