起初只是简单的事情,但对于XSLT新手来说却变得相当麻烦。
尝试对子节点进行排序/降序排列,但在将属性添加到它们的父节点后,在VS2010中调试时会收到错误消息:
“在已经添加文本、注释、处理指令或子元素节点之后无法向父元素添加属性和命名空间节点。”
假设我有这个简单的XML:
<posts>
<year value="2013">
<post postid="10030" postmonth="1">
<othernode></othernode>
<othernode2></othernode2>
</post>
<post postid="10040" postmonth="2">
<othernode></othernode>
<othernode2></othernode2>
</post>
<post postid="10050" postmonth="3">
<othernode></othernode>
<othernode2></othernode2>
</post>
</year>
<year value="2012">
<post postid="10010" postmonth="1">
<othernode></othernode>
<othernode2></othernode2>
</post>
<post postid="10015" postmonth="2">
<othernode></othernode>
<othernode2></othernode2>
</post>
<post postid="10020" postmonth="3">
<othernode></othernode>
<othernode2></othernode2>
</post>
</year>
</posts>
我向xmldatasource传递了一个XPATH以检索相关的<year>
节点,例如2013年。
然后我需要使用postid对其子节点<post>
进行降序排序,因此对于<year value=2013>
,当渲染时,postid = 10050将首先显示出来。
因此,要明确:我只对一个<year>
节点内部进行排序。
在我将节点拆分为单独的<post>
节点之前(即xml为/posts/post),以下XSLT有效:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" omit-xml-declaration="no"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()">
<xsl:sort select="@postid" data-type="text" order="descending"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
由于上述错误,在运行时xmldatasource为空。如果我将ascending传递到order中,显然会返回相同的xml(没有转换)。
问题:如何更新上面的XSLT(或新的XSLT)以容纳父节点属性(<year value="">
)?通过研究,有一个答案说“我需要在元素创建之前添加属性创建”。当观察调试器时,这很有道理,子节点按降序形成,但年份标签缺少其属性。但我真的不知道XSLT。看不出它太复杂了,只是不知道语言。
非常感谢任何帮助。谢谢
data-type="text"
?如果postid
的值长度不同,显然会产生错误的结果。 - Dimitre Novatchevdata-type="numeric"
更可取。 - JLRishedata-type="number"
。 - Dimitre Novatchevdata-type="number"
(我意识到我在我的评论中不小心打出了“numeric”)。由于我不能完全确定Jim的ID始终都是数字,所以我现在会将我的答案保留为它,等待他的澄清。 - JLRishe