xsl:使用多个元素对XML文件进行排序

前端之家收集整理的这篇文章主要介绍了xsl:使用多个元素对XML文件进行排序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在 XML文件中对一堆记录进行排序.诀窍是我需要为不同的节点使用不同的元素进行排序.举一个最简单的例子,我想这样做:给定一个xml文件
  1. <?xml version="1.0" encoding="utf-8" ?>
  2.  
  3. <buddies>
  4.  
  5. <person>
  6. <nick>Jim</nick>
  7. <last>Zulkin</last>
  8. </person>
  9.  
  10. <person>
  11. <first>Joe</first>
  12. <last>Bumpkin</last>
  13. </person>
  14.  
  15. <person>
  16. <nick>Pumpkin</nick>
  17. </person>
  18.  
  19. <person>
  20. <nick>Andy</nick>
  21. </person>
  22.  
  23. </buddies>

我想把它转换成

  1. Andy
  2. Joe Bumpkin
  3. Pumpkin
  4. Jim Zulkin

也就是说,可以通过名字,姓氏和缺口的任何子集列出人.
排序键是姓氏(如果它存在),否则它是昵称(如果它存在),否则是名字.

我在这里遇到困难,因为使用变量作为xsl:sort键是apparently not allowed.

我目前最好的镜头是进行两步转换:使用此样式表为每条记录添加一个特殊标记

  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  3.  
  4. <xsl:output omit-xml-declaration="no" indent="yes"/>
  5.  
  6. <!-- *** convert each person record into a person2 record w/ the sorting key *** -->
  7. <xsl:template match="/buddies">
  8. <buddies>
  9. <xsl:for-each select="person">
  10. <person2>
  11. <xsl:copy-of select="*"/>
  12. <!-- add the sort-by tag -->
  13. <sort-by>
  14. <xsl:choose>
  15. <xsl:when test="last"> <xsl:value-of select="last"/>
  16. </xsl:when>
  17. <xsl:otherwise>
  18. <xsl:choose>
  19. <xsl:when test="nick"> <xsl:value-of select="nick"/> </xsl:when>
  20. <xsl:otherwise> <xsl:value-of select="first"/> </xsl:otherwise>
  21. </xsl:choose>
  22. </xsl:otherwise>
  23. </xsl:choose>
  24. </sort-by>
  25. </person2>
  26. </xsl:for-each>
  27. </buddies>

然后对生成的xml进行排序

  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  3.  
  4. <xsl:template match="/buddies">
  5. <xsl:apply-templates>
  6. <xsl:sort select="sort-by"/>
  7. </xsl:apply-templates>
  8. </xsl:template>
  9.  
  10. <xsl:template match="person2">
  11. <xsl:value-of select="first"/>
  12. <xsl:value-of select="nick"/>
  13. <xsl:value-of select="last"/><xsl:text>
  14. </xsl:text>
  15. </xsl:template>

虽然这个两步转换有效,但我想知道是否有更优雅的方式一次性完成它?

您可以使用concat XPath函数
  1. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  2. <xsl:output method="text"/>
  3. <xsl:template match="/buddies">
  4. <xsl:apply-templates>
  5. <xsl:sort select="concat(last,nick,first)"/>
  6. </xsl:apply-templates>
  7. </xsl:template>
  8. <xsl:template match="person">
  9. <xsl:value-of select="concat(normalize-space(concat(first,' ',last)),'&#xA;')"/>
  10. </xsl:template>
  11. </xsl:stylesheet>

猜你在找的XML相关文章