Swing JList - 从文件读取和写入XML

时间:2015-06-16 23:49:51

标签: java xml swing jaxb unmarshalling

我已经看了几个关于这个主题的帖子,但没有一个解决方案对我有用。我有一个加载方法:“加载”事件应清除右侧面板,并调用load()方法。调用load()时,它应该在右侧面板中显示未编组的数据。

public void load() throws Exception {
JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Configuration config = (Configuration) jaxbUnmarshaller.unmarshal(new File("save.xml"));
    System.out.println(config.getComponent());

}

那么,问题是如何将XML文件的内容加载到JList中?

这是我的Configuration.java

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlAccessType;

@XmlAccessorType(XmlAccessType.FIELD)

@XmlType(name = "", propOrder = {
        "part"
})
@XmlRootElement(name = "Configuration")
public class Configuration {

    protected List<String> part;

    public List<String> getComponent() {
        if(part == null) {
            part = new ArrayList<String>();
        }
        return this.part;
    }
}

我让save方法正常工作,下面是我的java代码。希望这个帮助

public void load() throws Exception {

    }

    public void save() throws Exception {
        JAXBContext context = JAXBContext.newInstance(Configuration.class);
        Marshaller marshaller = context.createMarshaller();
        Configuration config = new Configuration();
        File file = new File("save.xml");
        List<String> printList = config.getComponent();
        for(int i = 0;i < list.getSize();i++) {
            printList.add((String) list.getElementAt(i));
        }
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(config, file);

0 个答案:

没有答案