您好我有一个类似于下面的XML,需要使用日期字段进行排序.
<root>
<Node1>
<date></date>
</Node1>
<Node1>
<date></date>
</Node1>
<Node1>
<date></date>
</Node1>
<Node1>
<date></date>
</Node1>
<Node2>
<date></date>
</Node2>
<Node2>
<date></date>
</Node2>
<Node2>
<date></date>
</Node2>
<Node2>
<date></date>
</Node2>
</root>
Run Code Online (Sandbox Code Playgroud)
我想根据日期(比如asc顺序)对XML进行排序,而不管日期是在Node1还是Node2下.实际上在Java代码中我有两个单独的列表,一个是Node1对象,另一个是Node2对象.我可以在java中按任意顺序对列表进行排序.但我需要对日期进行排序,而不考虑它在XML上出现的节点.在Java中以这种方式排序的最佳方法是什么?
实际上我使用Castor将java对象编组为XML.如果你知道这可以用Castor完成,那就太棒了!
我会使用 XSLT,它在排序日期方面存在问题,您需要解决这个问题,如果您可以控制它,最简单的方法是使用可排序的日期格式,例如 yyyymmdd
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="root">
<xsl:copy>
<xsl:apply-templates>
<xsl:sort data-type="number" select="date"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)