用Java排序XML [英] Sorting an XML in Java

查看:447
本文介绍了用Java排序XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我有类似下面的XML,需要使用日期字段进行排序。

Hello I have an XML similiar to below, which needed to be sorted using the date field.

<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>

我想根据日期(比如asc顺序)对XML进行排序,无论是否日期在Node1或Node2下。实际上在Java代码中我有两个单独的列表,一个是Node1对象,另一个是Node2对象。我可以在java中以任意顺序对列表进行排序。但是我需要对日期进行排序,而不管它在XML上出现的节点。 在Java中以这种方式排序的最佳方法是什么?

I would like to sort the XML based on the date(say asc order), irrespective of whether the date is under Node1 or Node2. Actually in Java code I have two seperate lists, one with Node1 objects and other with Node2 obects. I can sort the list in any order sperately inside java. But I need to have the dates sorted irrespective of the nodes it is apperaing on the XML. What is the best approach to sort this way in Java?

实际上我使用Castor将java对象编组为XML。如果你知道这可以用Castor完成,那就太棒了!

Actaully I am using Castor for marshalling the java objects to XML. If you know this can be done with Castor, that will be great!

推荐答案

我使用XSLT,它有排序日期的probs,你需要工作,最简单的方法,如果你可以控制它是具有可排序的日期格式,如yyyymmdd

I'd use XSLT, it has probs with sorting dates that you'll need to work round, simplest way if you can control it is to have sortable date format like 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>

这篇关于用Java排序XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆