Java 如何将 ArrayList 写入 XML 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21125998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:46:54  来源:igfitidea点击:

How to write an ArrayList to an XML file?

javaxmlarraylist

提问by 23k

I'm trying to store an ArrayListinto an XML file so that I can retrieve the information later on and then display it back into the console.

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

Can someone show me the most effective way to do this?

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

EDIT:

编辑:

Heres what I am trying to write into an external file

这是我试图写入外部文件的内容

// 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);

This all creates a Bank user, which gets thrown into an ArrayList, then I want to store their information so that I can come back later and redisplay it.

这一切都创建了一个 Bank 用户,该用户被扔进了一个ArrayList,然后我想存储他们的信息,以便我以后可以回来并重新显示它。

采纳答案by kedark

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

// Modify this below class as per your need

// 根据您的需要修改下面的类

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

// below class actually writed

// 下面的类实际编写

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

回答by djangofan

The way I do it is either using XStream or Hymanson API (preferred) to serialize the java object to either a XML or a JSON file.

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

For example, see my XStream data providerI wrote for use with TestNG or JUnit parameterized tests.

例如,请参阅我编写的用于 TestNG 或 JUnit 参数化测试的XStream 数据提供程序

回答by Chai

How about using XMLEncoder/XMLDecoder?

使用 XMLEncoder/XMLDecoder 怎么样?

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

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

Copy and paraphrasing from the javadoc.

从 javadoc 复制和释义。

ArrayList arr = new ArrayList();
// populate your array
XMLEncoder e = new XMLEncoder(BufferedOutputStream(
                          new FileOutputStream("Test.xml")));
   e.writeObject(arr);
   e.close();

Similarly, the reverse to decode.

同样,反向解码。