如何编写一个ArrayList到一个XML文件? [英] How to write an ArrayList to an XML file?

查看:765
本文介绍了如何编写一个ArrayList到一个XML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个的ArrayList 存储到一个XML文件,这样我以后可以检索信息,然后显示它放回控制台。

有人能告诉我这样做的最有效的方法是什么?

编辑:

下面有什么,我想写到外部文件

  //创建新用户
        银行银行=新银行();        的System.out.println(请在下面输入(例如:John M. Smith)的您的全名:);
        字符串名称= scanner.nextLine();
        的System.out.println(创建一个用户名:);
        字符串username = scanner.nextLine();
        的System.out.println(请输入您的起始存款金额:);
        INT余额= scanner.nextInt();        System.out.print(破折号);
        System.out.print(生成您的信息...... \\ n);
        System.out.print(破折号);        INT引脚= bank.PIN();
        串accountNum = bank.accountNum();        用户的用户=新用户(名称,用户名,销,accountNum,平衡);        //新用户被添加到数组列表
        Bank.users.add(用户);        的System.out.println(用户);

这都创建了一个银行用户,它被扔进一个的ArrayList ,那么我想存储他们的信息,这样我就可以回来以后,并重新显示。


解决方案

 公共静态无效的主要(字串[] args){
    // TODO自动生成方法存根    WriteFile的OB =新WriteFile的();
    ArrayList的列表=新的ArrayList();
    list.add(新的细节(A,20,1));
    list.add(新的信息(B,30,2));    ob.writeXmlFile(名单);
}

//修改此下方类根据自己的需要

 类的细节{
字符串名称;公共字符串的getName(){
    返回名称;
}公共无效setname可以(字符串名称){
    this.name =名称;
}公众诠释getAge(){
    返回年龄;
}公共无效setAge(INT年龄){
    this.age =年龄;
}公众诠释的getId(){
    返回ID;
}公共无效SETID(INT ID){
    this.id = ID;
}INT年龄;
INT ID;公开信息(){
}公共信息(字符串名_,诠释age_,诠释ID_){
    名称=名_;
    年龄= age_;
    ID = ID_;
}

//下面类实际上所著

 公共无效writeXmlFile(ArrayList的<详情>名单){    尝试{        的DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
        的DocumentBuilder构建= dFact.newDocumentBuilder();
        文档的文档= build.newDocument();        元根= doc.createElement(Studentinfo);
        doc.appendChild(根);        元素详细= doc.createElement(详细信息);
        root.appendChild(详细信息);
        对于(详细信息DTL:名单){            元素名称= doc.createElement(名称);
            name.appendChild(doc.createTextNode(将String.valueOf(DTL
                    .getName())));
            Details.appendChild(名);            元素ID = doc.createElement(ID);
            id.appendChild(doc.createTextNode(将String.valueOf(dtl.getId())));
            Details.appendChild(ID);            元素MMI = doc.createElement(时代);
            mmi.appendChild(doc.createTextNode(将String.valueOf(dtl.getAge())));
            Details.appendChild(MMI);        }        //将文档保存到磁盘文件
        TransformerFactory的tranFactory = TransformerFactory.newInstance();
        变压器aTransformer = tranFactory.newTransformer();        //很好地格式化XML
        aTransformer.setOutputProperty(OutputKeys.ENCODING,ISO-8859-1);        aTransformer.setOutputProperty(
                {http://xml.apache.org/xslt}indent-amount,4);
        aTransformer.setOutputProperty(OutputKeys.INDENT,是);        DOMSource的源=新DOMSource的(DOC);
        尝试{
            // XML文件的位置和名称,您可以根据需要改变
            FileWriter的FOS =新的FileWriter(./ ros.xml);
            StreamResult结果=新的StreamResult(FOS);
            aTransformer.transform(源,结果);        }赶上(IOException异常五){            e.printStackTrace();
        }    }赶上(TransformerException中前){
        的System.out.println(错误输出文件);    }赶上(前的ParserConfigurationException){
        的System.out.println(错误建筑文档);
    }
}

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

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.

解决方案

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

这篇关于如何编写一个ArrayList到一个XML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆