XSLT不会按字母顺序按xml字段排序

时间:2015-10-21 02:48:07

标签: xml sorting xslt

我试图通过" ownerName"中的姓氏字段对这些数据进行排序。这种排序代码是否在正确的位置?当我尝试运行它时,它给我一个解析错误。

    <xsl:apply-templates select="storeloation" /><br/>
    <xsl:apply-templates select="storeURL" /><br/>
    <xsl:apply-templates select="storeDescription" /><br/>
    <xsl:apply-templates select="related stores" /><br/>
    <xsl:apply-templates select="storecustomerCount" /><br/>
    <xsl:apply-templates select="storeVisits" /><br/>
    <xsl:apply-templates select="storeestablished" /><br/>
    <xsl:apply-templates select="ownersProfile/ownersName/firstName"/>
    <xsl:apply-templates select="ownersProfile/ownersName/surname"/>
        <xsl:sort select="surname" /><br/>
    <xsl:apply-templates select="ownersProfile/ownersEmail"/><br/>
    <xsl:apply-templates select="ownersProfile/ownersAddress"/><br/>

如果我没有弄错(我可能是这样)这种排序声明,那么模板匹配的每个实例都会按照所有者的姓氏进行短排序吗?

1 个答案:

答案 0 :(得分:1)

这里有两个错误。

首先,解析错误是因为xsl:sort应该是xsl:apply-templates的子节点,而不是兄弟节点。

其次,评估xsl:sort的选择表达式,并将序列中的每个项目排序为上下文节点。您的案例中的这些项目是surname个元素。我怀疑surname个元素没有名为surname的子元素;而你的意图是<xsl:sort select="."/>

所以正确的形式是:

<xsl:apply-templates select="ownersProfile/ownersName/surname">
        <xsl:sort select="." />
</xsl:apply-templates>
<br/>

顺便说一句,如果你告诉我们错误是什么,我们大多数人发现诊断“解析错误”要容易得多。说一些事情失败而不说它失败的方式就像告诉你的医生你痛苦而不说疼痛在哪里。

== ON REFLECTION ... ==

你没有展示你的XML源,但考虑到元素名称可能意味着什么,我怀疑有多个ownersProfile元素,每个都有一个ownerName,它有一个或多个firstNames和一个姓氏,还有其他属性,比如电子邮件地址。在这种情况下,您不想对姓氏进行排序,而是要对配置文件进行排序。所以它变成了这样的东西:

<xsl:for-each select="ownersProfile">
  <xsl:sort select="ownersName/surname"/>
    <xsl:apply-templates select="ownersName/firstName"/>
    <xsl:apply-templates select="ownersName/surname"/>
    <xsl:apply-templates select="ownersEmail"/><br/>
    <xsl:apply-templates select="ownersAddress"/><br/>
   ...
</xsl:for-each>

但我现在完全陷入了猜测的境界。