1.动物园新进了3头大象:
胖胖,2岁,1.2吨;
肥仔,1岁,1.5吨;
憨憨,3岁,1.8吨;
还有3只猴子:
星仔,3岁,0.8米;
狒狒,4岁,0.9米;
猴哥,5岁,1.0米;
它们的信息存在了集合中,现在动物管理员需要将这些宝贝们的信息存入xml中保存.请你写一个程序,结合面向对象,和dom4j技术,帮管理员实现这个功能。
Animal类
public class Animal {
private String name;
private int age;
public Animal() {
}
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Elephant类
public class Elephant extends Animal {
private double weight;
public Elephant() {
}
public Elephant(double weight) {
this.weight = weight;
}
public Elephant(String name, int age, double weight) {
super(name, age);
this.weight = weight;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
Monkey类
private double height;
public Monkey() {
}
public Monkey(double height) {
this.height = height;
}
public Monkey(String name, int age, double height) {
super(name, age);
this.height = height;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
Test1类
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import java.io.FileOutputStream;
import java.util.ArrayList;
public class Test1 {
public static void main(String[] args) throws Exception {
ArrayList<Animal> animals = new ArrayList<>();
animals.add(new Elephant("胖胖",2,1.3));
animals.add(new Elephant("肥仔",1,1.5));
animals.add(new Elephant("憨憨",3,1.8));
animals.add(new Monkey("星仔",3,0.8));
animals.add(new Monkey("狒狒",4,0.9));
animals.add(new Monkey("猴哥",5,1.0));
createXml(animals);
}
public static void createXml(ArrayList<Animal> animals) throws Exception {
//创建一个dom树
Document doc = DocumentHelper.createDocument();
//添加根节点
Element ani = doc.addElement("animals");
//遍历集合
for (int i = 0; i < animals.size(); i++) {
//添加子节点
Element a = ani.addElement("animal");
//给子节点添加子节点
Element name = a.addElement("name");
name.setText(animals.get(i).getName());
Element age = a.addElement("age");
//age.setText(Integer.toString(animals.get(i).getAge()));
//age.setText(String.valueOf(animals.get(i).getAge()));
age.setText(animals.get(i).getAge()+"岁");
//判断 是大象还是猴子
if(animals.get(i) instanceof Elephant){
Element weight = a.addElement("weight");
weight.setText(((Elephant) animals.get(i)).getWeight()+"吨");
}else {
Element height = a.addElement("height");
height.setText(((Monkey) animals.get(i)).getHeight()+"米");
}
}
//写入xml中
FileOutputStream out = new FileOutputStream("D:\\IdeaworkSpace\\day22-java22\\src\\animal");
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(out, format);
writer.write(doc);
writer.close();
}
}