我们需要按特定元素对输入XML进行排序,并在每组记录中分配序列号。
在下面的示例XML中,是否可以按类型对节点进行排序,并为与特定类型对应的节点分配序列号?如果有2个节点的流派为“幻想”,则它们需要一起显示,并且应在每个记录中添加一个标记,以显示每个类型中的记录编号。
谢谢!
XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:key name="bookGenre" match="Book" use="genre" />
<xsl:template match="Books">
<Books>
<xsl:apply-templates select="Book[generate-id(.)=generate-id(key('bookGenre',genre)[1])]"/>
</Books>
</xsl:template>
<xsl:template match="Book">
<xsl:for-each select="key('bookGenre', genre)">
<Book>
<genre><xsl:value-of select="genre" /></genre>
<author><xsl:value-of select="author" /></author>
<title><xsl:value-of select="title" /></title>
<price><xsl:value-of select="price" /></price>
<groupSeqId><xsl:value-of select="position()" /></groupSeqId>
</Book>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
输入XML:
<Books>
<Book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
</Book>
<Book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>$5.95</price>
</Book>
<Book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fiction</genre>
<price>5.95</price>
</Book>
<Book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>$12</price>
</Book>
<Book id="bk105">
<author>Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fiction</genre>
<price>5.95</price>
</Book>
</Books>
预期输出XML:
<Books>
<Book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<groupSeqId>1</groupSeqId>
</Book>
<Book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>$5.95</price>
<groupSeqId>1</groupSeqId>
</Book>
<Book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>$12</price>
<groupSeqId>2</groupSeqId>
</Book>
<Book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fiction</genre>
<price>5.95</price>
<groupSeqId>1</groupSeqId>
</Book>
<Book id="bk105">
<author>Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fiction</genre>
<price>5.95</price>
<groupSeqId>2</groupSeqId>
</Book>
</Books>