动物园新进了3头大象:
胖胖,2岁,1.2吨;
肥仔,1岁,1.5吨;
憨憨,3岁,1.8吨;
还有3只猴子:
星仔,3岁,0.8米;
狒狒,4岁,0.9米;
猴哥,5岁,1.0米;
它们的信息存在了集合中,现在动物管理员需要将这些宝贝们的信息存入xml中保存.请你写一个程序,结合面向对象,和dom4j技术,帮管理员实现这个功能。
1.首先创建动物类作为父类
public class Animal {
private String name;
private int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public Animal() {
}
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;
}
}
2.再创建两个子类
大象类(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)
public class Monkey extends Animal {
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;
}
}
3.最后测试类
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.*;
import java.util.ArrayList;
public class AnimalTest {
public static void main(String[] args) throws Exception{
ArrayList<Animal> animals = new ArrayList<>();
animals.add(new Elephant("胖胖",2,1.2));
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));
Xmlcreat(animals);
}
public static void Xmlcreat(ArrayList<Animal> animals) throws IOException {
//创建DOM数
Document document = DocumentHelper.createDocument();
//添加根节点
Element animals1 = document.addElement("animals");
//遍历集合
for (int i = 0; i < animals.size(); i++) {
//添加子节点
Element animal = animals1.addElement("animal");
//再给子节点添加子节点
Element name = animal.addElement("name");
name.setText(animals.get(i).getName());
Element age = animal.addElement("age");
age.setText(animals.get(i).getAge()+"岁");
//判断是大象还是猴子
if (animals.get(i) instanceof Elephant){
Element weight = animal.addElement("weight");
weight.setText(((Elephant)animals.get(i)).getWeight()+"吨");
}else{
Element height = animal.addElement("height");
height.setText(((Monkey)animals.get(i)).getHeight()+"米");
}
}
//写入xml中
// FileOutputStream out = new FileOutputStream("/src/day22/HomeWork.xml");
// OutputFormat format = OutputFormat.createPrettyPrint();
// XMLWriter writer = new XMLWriter(out, format);
// writer.write(document);
// writer.close();
String s = System.getProperty("user.dir") + "/src/day22/HomeWork.xml";
FileWriter fileWriter = new FileWriter(s);
document.write(fileWriter);
fileWriter.close();
}
}
运行完成以后查看xml文档