我有以下 XML:
<Users>
<User Id="1">
<Name>abc</Name>
<LastName>d</LastName>
</User>
<User Id="2">
<Name></Name>
<LastName>ab</LastName>
</User>
<User Id="3">
<Name>a</Name>
<LastName>efg</LastName>
</User>
</Users>
现在我使用以下模板对用户进行排序:
<xsl:template match="Users">
<Users>
<xsl:for-each select="User">
<xsl:sort select="Name"/>
<xsl:sort select="LastName"/>
<User>
<xsl:attribute name="Id">
<xsl:value-of select="attribute::Id"/>
</xsl:attribute>
<Name>
<xsl:value-of select="Name"/>
</Name>
<LastName>
<xsl:value-of select="LastName"/>
</LastName>
</User>
</xsl:for-each>
</Users>
</xsl:template>
但我需要排序,它满足以下条件:按名称排序。如果 Name 为空或 null,我需要按 LastName 排序。所以在生成的 XML 中,我需要以下顺序:User3、User2、User1。
感谢任何帮助。
附言:我使用 ASP.NET 3.5
最佳答案
我会先使用身份转换,然后将排序应用于元素的并集(不包括那些 Name
为空的元素)
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Users">
<xsl:copy>
<xsl:apply-templates select="User">
<xsl:sort select="Name[.!='']|LastName"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
当应用于问题中显示的输入时,我们获得:
<Users>
<User Id="3">
<Name>a</Name>
<LastName>efg</LastName>
</User>
<User Id="2">
<Name/>
<LastName>ab</LastName>
</User>
<User Id="1">
<Name>abc</Name>
<LastName>d</LastName>
</User>
</Users>
关于c# - XSLT 条件排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6719449/