如何将ArrayList写入XML文件?

时间:2014-01-14 23:09:18

标签: java xml arraylist

我正在尝试将ArrayList存储到XML文件中,以便稍后可以检索该信息,然后将其显示回控制台。

有人能告诉我最有效的方法吗?

编辑:

下面是我要写入外​​部文件的内容

// new user is created
Bank bank = new Bank();

System.out.println("Enter your full name below (e.g. John M. Smith): ");
String name = scanner.nextLine();
System.out.println("Create a username: ");
String userName = scanner.nextLine();
System.out.println("Enter your starting deposit amount: ");
int balance = scanner.nextInt();

System.out.print(dash);
System.out.print("Generating your information...\n");
System.out.print(dash);

int pin = bank.PIN();
String accountNum = bank.accountNum();

User user = new User(name, userName, pin, accountNum, balance);

//new user gets added to the array list
Bank.users.add(user);

System.out.println(user);

这一切都会创建一个Bank用户,它会被投入ArrayList,然后我想存储他们的信息,以便我可以稍后再回来重新显示它。

3 个答案:

答案 0 :(得分:3)

public static void main(String[] args) {
    // TODO Auto-generated method stub

    WriteFile ob = new WriteFile();
    ArrayList list = new ArrayList();
    list.add(new details("A", 20, 1));
    list.add(new details("B", 30, 2));

    ob.writeXmlFile(list);
}

//根据您的需要修改下面的课程

class details {
String name;

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;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

int age;
int id;

public details() {
}

public details(String name_, int age_, int id_) {
    name = name_;
    age = age_;
    id = id_;
}

//下面的课实际写了

public void writeXmlFile(ArrayList<details> list) {

    try {

        DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
        DocumentBuilder build = dFact.newDocumentBuilder();
        Document doc = build.newDocument();

        Element root = doc.createElement("Studentinfo");
        doc.appendChild(root);

        Element Details = doc.createElement("Details");
        root.appendChild(Details);


        for (details dtl : list) {

            Element name = doc.createElement("Name");
            name.appendChild(doc.createTextNode(String.valueOf(dtl
                    .getName())));
            Details.appendChild(name);

            Element id = doc.createElement("ID");
            id.appendChild(doc.createTextNode(String.valueOf(dtl.getId())));
            Details.appendChild(id);

            Element mmi = doc.createElement("Age");
            mmi.appendChild(doc.createTextNode(String.valueOf(dtl.getAge())));
            Details.appendChild(mmi);

        }

        // Save the document to the disk file
        TransformerFactory tranFactory = TransformerFactory.newInstance();
        Transformer aTransformer = tranFactory.newTransformer();

        // format the XML nicely
        aTransformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");

        aTransformer.setOutputProperty(
                "{http://xml.apache.org/xslt}indent-amount", "4");
        aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");

        DOMSource source = new DOMSource(doc);
        try {
            // location and name of XML file you can change as per need
            FileWriter fos = new FileWriter("./ros.xml");
            StreamResult result = new StreamResult(fos);
            aTransformer.transform(source, result);

        } catch (IOException e) {

            e.printStackTrace();
        }

    } catch (TransformerException ex) {
        System.out.println("Error outputting document");

    } catch (ParserConfigurationException ex) {
        System.out.println("Error building document");
    }
}

答案 1 :(得分:1)

我这样做的方法是使用XStream或Jackson API(首选)将java对象序列化为XML或JSON文件。

例如,请参阅我编写的用于TestNG或JUnit参数化测试的XStream data provider

答案 2 :(得分:1)

如何使用XMLEncoder / XMLDecoder?

http://docs.oracle.com/javase/6/docs/api/java/beans/XMLEncoder.html

从javadoc复制和释义。

new GradientPaint(0, 0, Color.RED, 0, 1000, Color.BLUE)

同样,反向解码。