汽类:package day2.domx;public class Car implements Comparable{ private String band;//车牌 private String place;//产地 private String time; //出产日期 private int price; //单价 public Car(){} public String getBand() { return band; } public void setBand(String band) { this.band = band; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public int compareTo(Car car) { if(this.price car.getPrice()) { return -1; }else { return 0; } }}car.xml<?xml version="1.0" encoding="UTF-8"?> 奥迪车牌> 北京产地> 40单价> 汽车> 本田车牌> 广州产地> 60单价> 汽车> 车辆清单>
排序代码:import java.io.File;import java.util.ArrayList;import java.util.Collections;import java.util.List;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.junit.Test;public class Demo3 { @Test public void paixu() throws Exception { SAXReader saxread = new SAXReader(); Document document = saxread.read(new File("src/day2/domx/car.xml")); List elementlist = document.getRootElement().elements(); List carList = new ArrayList(); //存对象信息 for(Element el:elementlist) { Car car = new Car(); car.setBand(el.elementText("车牌号")); car.setPlace("产地"); car.setTime(el.element("车牌").attributeValue("出产时间")); car.setPrice(Integer.parseInt(el.elementText("单价"))); carList.add(car); } System.out.println("按单价排序前:"); show(carList); //System.out.println("按单价排序后:"); //sortByPriceDesc(carList); } private void sortByPriceDesc(List carList) { Collections.sort(carList); show(carList); } private void show(List carList) { if(carList!=null && carList.size()>0){ for(Car car : carList){ System.out.print("车牌:"+car.getBand()+"\t"); System.out.print("产地:"+car.getPlace()+"\t"); System.out.print("单价:"+car.getPrice()+"\t"); System.out.println("出产时间:"+car.getTime()); } } }}