汽类:
package day2.domx; public class Car implements Comparable<Car>{ 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 if(this.price > car.getPrice()) { return -1; }else { return 0; } } } car.xml <?xml version="1.0" encoding="UTF-8"?> <车辆清单> <汽车> <车牌 出产时间="2010年">奥迪</车牌> <产地>北京</产地> <单价>40</单价> </汽车> <汽车> <车牌 出产时间="2011年">本田</车牌> <产地>广州</产地> <单价>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<Element> elementlist = document.getRootElement().elements(); List<Car> carList = new ArrayList<Car>(); //存对象信息 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<Car> carList) { Collections.sort(carList); show(carList); } private void show(List<Car> 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()); } } } }原文链接:https://www.f2er.com/xml/293391.html