将名称从ArrayList写入XML文件

时间:2017-02-17 21:58:37

标签: java xml class

我正在尝试将ArrayList中的乘客姓名写入XML文件。我必须将XML文档创建的代码放入我的Aircraft类中。以下是我的飞机类代码。这还包括我的主调用方法App.java的代码。这两个类都没有错误;但是,我的一部分认为它没有正确创建XML文件。我想知道是否必须在App.java中的任何位置调用writeNames()方法才能使其正常工作?

飞机类:

import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Aircraft {

    private double maxSpeed;
    private int maxPassengers;
    private int numEngines;

    private Pilot pilot;
    private Stewardess stewardess;
    private ArrayList<Passenger> passengers;

    Aircraft(double maxSpeed, int maxPassengers, int numEngines, Pilot pilot, 
        Stewardess stewardess, ArrayList<Passenger> passengers)
{
    this.pilot = pilot;
    this.stewardess = stewardess;
    this.passengers = passengers;
    this.maxSpeed = maxSpeed;
    this.maxPassengers = maxPassengers;
    this.numEngines = numEngines;
}

public String getInfo()
{
    return "Aircraft" + "\n" + "Max Speed: " + this.maxSpeed + " mph " + "\n" + 
           "Max Passengers: " + this.maxPassengers + " passengers " + "\n" + "Number of Engines: " + 
           this.numEngines + " engines" + "\n" + "\n" + this.pilot.getInfo() + "\n" + "\n" + "Stewardess" 
           + this.stewardess.getInfo() + "\n" + "\n" + "Passenger 1" + passengers.get(0).getInfo() + "\n"+ "\n" + "Passenger 2" 
           + passengers.get(1).getInfo() + "\n" + "\n" + "Passenger 3" + passengers.get(2).getInfo() + "\n" + "\n" + "Passenger 4" 
           + passengers.get(3).getInfo();
}

public ArrayList<String> writeNames(ArrayList<String> passengers)
{
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;            

        builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Element xmlRoot = document.createElement("Passengers");
        document.appendChild(xmlRoot);

        Element passenger;
        Element name;

        //passenger1
        passenger = document.createElement("Passenger");
        passenger.setAttribute("id", "1");

        name = document.createElement("Name");
        name.appendChild(document.createTextNode(passengers.get(0)));
        passenger.appendChild(name);

        xmlRoot.appendChild(passenger);

        //passenger2
        passenger = document.createElement("Passenger");
        passenger.setAttribute("id", "2");

        name = document.createElement("Name");
        name.appendChild(document.createTextNode(passengers.get(1)));
        passenger.appendChild(name);

        xmlRoot.appendChild(passenger);

        //passenger3
        passenger = document.createElement("Passenger");
        passenger.setAttribute("id", "3");

        name = document.createElement("Name");
        name.appendChild(document.createTextNode(passengers.get(2)));
        passenger.appendChild(name);

        xmlRoot.appendChild(passenger);

        //passenger4
        passenger = document.createElement("Passenger");
        passenger.setAttribute("id", "4");

        name = document.createElement("Name");
        name.appendChild(document.createTextNode(passengers.get(3)));
        passenger.appendChild(name);

        xmlRoot.appendChild(passenger);            

        //Write document to file
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult("src/passengers.xml");
        transformer.transform(source, result);            

    } catch (Exception e) {
        e.printStackTrace();
    }
    return passengers;
} 

}

App.java:

import java.util.ArrayList;

public class App {

public static void main(String[] args) {

    //Four roommates that share same address, have different suitcases, traveling to different destinations
    Address address = new Address("University Park", "PA", "16802");        
    Suitcase suitcase1 = new Suitcase(7, 75, "Carry Strap");
    Suitcase suitcase2 = new Suitcase(5, 70, "No Carry Strap");
    Suitcase suitcase3 = new Suitcase(4, 60, "No Carry Strap");
    Suitcase suitcase4 = new Suitcase(8, 55, "Carry Strap");

    //Stewardess Info
    Suitcase suitcaseStewardess = new Suitcase(4, 40, "No Carry Strap");
    Address addressStewardess = new Address("Doylestown", "PA", "18902");
    Stewardess stewardess = new Stewardess(4, "Full Time", 40, suitcaseStewardess, addressStewardess);

    //Pilot Info
    Suitcase suitcasePilot = new Suitcase(10, 50, "Carry Strap");
    Address addressPilot = new Address("Raliegh", "NC", "27513");
    Map map = new Map(14000.5, "United States", "Northeast");
    Pilot pilot = new Pilot(7, 40, "Perfect", suitcasePilot, map, addressPilot);

    //Passenger Info
    ArrayList<Passenger> passengers = new ArrayList<>();
    passengers.add(new Passenger("Luke Harding", 1400, "England", "First Class - A14", suitcase1, address));
    passengers.add(new Passenger("Dalton Sydnor", 1000, "Mexico", "First Class - G7", suitcase2, address));
    passengers.add(new Passenger("Ian Smithgall", 700, "Russia", "First Class - C4", suitcase3, address));
    passengers.add(new Passenger("Matt Yohe", 850, "Indiana", "First Class - B1", suitcase4, address));

    //Aircraft Info
    Aircraft aircraft = new Aircraft (750, 400, 4, pilot, stewardess, passengers);

    System.out.println(aircraft.getInfo());  
}

}

2 个答案:

答案 0 :(得分:1)

同样,如果这是我的问题,我会使用JAXB将我的Java类编组为XML并重新编写,因为这需要手动创建XML文档的所有烦躁部分。图书馆。

要使用ArrayLists,您可以使用@XmlElementWrapper注释对其进行注释。

例如,如果您有一个带有教师字段的课堂课程,一个maxStudent字段,一个maxStudents字段,您可以使用JAXB注释创建您的类,如下所示:

@XmlRootElement(name = "person")
@XmlAccessorType(XmlAccessType.FIELD)
class Person { // base class
    @XmlElement(name = "first_name")
    private String firstName;
    @XmlElement(name = "last_name")
    private String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Person() {
        // Default constructors are required
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
    }

}

@XmlRootElement(name = "teacher")
@XmlAccessorType(XmlAccessType.FIELD)
class Teacher extends Person {
    @XmlElement(name = "grade_level")
    private String gradeLevel;

    public Teacher(String firstName, String lastName, String gradeLevel) {
        super(firstName, lastName);
        this.gradeLevel = gradeLevel;
    }

    public Teacher() {
        // Default constructors are required
    }

    public String getGradeLevel() {
        return gradeLevel;
    }

    public void setGradeLevel(String gradeLevel) {
        this.gradeLevel = gradeLevel;
    }

    @Override
    public String toString() {
        return "Teacher [gradeLevel=" + gradeLevel + ", getFirstName()=" + getFirstName() + ", getLastName()="
                + getLastName() + "]";
    }

}

@XmlRootElement(name = "student")
@XmlAccessorType(XmlAccessType.FIELD)
class Student extends Person {
    @XmlElement(name = "age")
    private int age;

    public Student(String firstName, String lastName, int age) {
        super(firstName, lastName);
        this.age = age;
    }

    public Student() {

    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student [age=" + age + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]";
    }

}

@XmlRootElement(name = "class_room")
@XmlType(propOrder = {"teacher", "maxStudents", "students"})
@XmlAccessorType(XmlAccessType.FIELD)
class ClassRoom {
    @XmlElementRef
    private Teacher teacher;
    @XmlElementWrapper(name = "students")
    @XmlElement(name = "student")
    private List<Student> students = new ArrayList<>();
    @XmlElement(name = "max_students")
    int maxStudents;

    public ClassRoom(Teacher teacher, int maxStudents) {
        this.teacher = teacher;
        this.maxStudents = maxStudents;
    }

    public ClassRoom() {

    }

    public void addStudent(Student student) {
        students.add(student);
    }

    public List<Student> getStudents() {
        return students;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public int getMaxStudents() {
        return maxStudents;
    }

    @Override
    public String toString() {
        return "ClassRoom [teacher=" + teacher + ", students=" + students + ", maxStudents=" + maxStudents + "]";
    }

}

然后只需几段代码就可以将它们编组为XML:

// create and fill my class room
ClassRoom classRoom = new ClassRoom(new Teacher("John", "Smith", "Four"), 30);
classRoom.addStudent(new Student("Bill", "Jones", 11));
classRoom.addStudent(new Student("Cathy", "Franks", 12));
classRoom.addStudent(new Student("Henry", "Rotter", 11));
classRoom.addStudent(new Student("Barry", "Edwards", 11));
classRoom.addStudent(new Student("Daffy", "Duck", 10));
classRoom.addStudent(new Student("Mickey", "Mouse", 11));
classRoom.addStudent(new Student("Donald", "Trump", 11));

try {
    // marshall to XML
    JAXBContext context = JAXBContext.newInstance(ClassRoom.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(classRoom, System.out);
} catch (JAXBException e) {
    e.printStackTrace();
}

将返回:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<class_room>
    <teacher>
        <first_name>John</first_name>
        <last_name>Smith</last_name>
        <grade_level>Four</grade_level>
    </teacher>
    <max_students>30</max_students>
    <students>
        <student>
            <first_name>Bill</first_name>
            <last_name>Jones</last_name>
            <age>11</age>
        </student>
        <student>
            <first_name>Cathy</first_name>
            <last_name>Franks</last_name>
            <age>12</age>
        </student>
        <student>
            <first_name>Henry</first_name>
            <last_name>Rotter</last_name>
            <age>11</age>
        </student>
        <student>
            <first_name>Barry</first_name>
            <last_name>Edwards</last_name>
            <age>11</age>
        </student>
        <student>
            <first_name>Daffy</first_name>
            <last_name>Duck</last_name>
            <age>10</age>
        </student>
        <student>
            <first_name>Mickey</first_name>
            <last_name>Mouse</last_name>
            <age>11</age>
        </student>
        <student>
            <first_name>Donald</first_name>
            <last_name>Trump</last_name>
            <age>11</age>
        </student>
    </students>
</class_room>

答案 1 :(得分:0)

是的,根据您提供的代码,如果您想将乘客写入XML文件,您需要调用Aircraft的writePassengers方法并传入您想要写的乘客列表。

这似乎没有意义,因为您在创建类时在本地设置乘客列表,并且仍然需要将其作为方法中的参数。您应该能够删除参数并仍具有适当的功能:

public ArrayList<String> writeNames()

然后您可以在创建Airplane类后调用App类中的函数,如下所示:

aircraft.writeNames()