【发布时间】:2011-04-23 03:04:40
【问题描述】:
我有一个需要排序的 XML 文件。在使用它的开发人员告诉我将 XML 更改为我拥有的具有 type=label 属性的项目之前,它工作得很好,以标记节点。 XSLT 不是很好。需要在“排序”节点上进行排序。
(简化的)XML 如下所示:
<rss>
<channel>
<title>This is the title</title>
<link>http://www.mydomain.com/</link>
<description>The Description</description>
<label>
<title>Another Label</title>
<sort>4</sort>
</label>
<item>
<title>An Item</title>
<sort>2</sort>
</item>
<item>
<title>One Item</title>
<sort>3</sort>
</item>
<label>
<title>A Label</title>
<sort>1</sort>
</label>
</channel>
</rss>
旧的 XSL(当我只是对“项目”进行排序时)看起来像这样:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" encoding="UTF-8" indent="yes" />
<xsl:template match="channel">
<rss>
<channel>
<xsl:copy-of select="title"/>
<xsl:copy-of select="link"/>
<xsl:copy-of select="description"/>
<xsl:apply-templates select="item">
<xsl:sort select="sort" data-type="number"/>
</xsl:apply-templates>
</channel>
</rss>
</xsl:template>
<xsl:template match="item">
<xsl:copy-of select="." />
</xsl:template>
</xsl:stylesheet>
尝试了这个想法,它会起作用,而且大部分都可以,但我得到了各种各样的“落后者”。
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" encoding="UTF-8" />
<xsl:template match="channel">
<rss>
<channel>
<xsl:copy-of select="title"/>
<xsl:copy-of select="link"/>
<xsl:copy-of select="description"/>
<xsl:apply-templates>
<xsl:sort select="sort"/>
</xsl:apply-templates>
</channel>
</rss>
</xsl:template>
<xsl:template match="item">
<xsl:copy-of select="." />
</xsl:template>
<xsl:template match="label">
<xsl:copy-of select="." />
</xsl:template>
</xsl:stylesheet>
使用最新的 XSL 完成所有操作后,“落后者”看起来像这样:
<rss xmlns:st="http://ww2.startribune.com/rss/modules/base/">
<channel>
<title>A Title</title>
<link>http://www.mydomain.com/</link>
<description>The Description</description>
A Title
http://www.mydomain.com/
The Description
<label>...
<item>...
【问题讨论】:
-
“落后者”的发生是由于 XSLT 引擎提供的默认匹配模板。由于您在频道模板中显式处理标题、链接和描述元素,因此您需要为它们创建空模板以吸收文本。您的一般应用模板调用是触发默认模板的原因。
-
@ewh - 你应该发表你的评论作为答案,我会投赞成票。
-
@ewh - 这些空模板是什么样的,它们去哪里了?我了解“应用模板”对 select=item 做了什么,看看它现在在做什么。我怎样才能让它根据公共的“排序”子节点对标签和项目进行排序?
-
查看我的答案以获得更语义正确的解决方案,该解决方案依赖于标准
xsl:sort行为。