需要帮助解组XML到Java

时间:2017-03-29 09:46:34

标签: java xml jaxb

我目前正在开发一个小项目,我必须将JList编组/解组为XML文件。以下代码正在工作(在某种程度上),但我需要帮助改进它。

以下是代码:

import java.awt.EventQueue;

import javax.swing.AbstractListModel;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import java.io.File;
import java.util.List;

import javax.swing.JMenu;
import javax.swing.JList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Window {

    private JFrame frame;

    /**
     * Launch the application. The main method is the entry point to a Java application. 
     * For this assessment, you shouldn't have to add anything to this.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Window window = new Window();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application. This is the constructor for this Window class.
     * All of the code here will be executed as soon as a Window object is made.
     */
    public Window() {
        initialize();
    }

    /**
     * Initialize the contents of the frame. This is where Window Builder
     * will generate its code.
     */
    public void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 614, 584);
        frame.setTitle("Pc part builder");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        //menu and menu items
        JMenuBar menuBar = new JMenuBar();
        menuBar.setBounds(0, 0, 161, 35);
        frame.getContentPane().add(menuBar);

        JMenu mnNewMenu = new JMenu("File");
        menuBar.add(mnNewMenu);
        JMenuItem mntmNewMenuItem = new JMenuItem("Load");
        mntmNewMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                load();
            }
        });
        mnNewMenu.add(mntmNewMenuItem);

        JMenuItem mntmNewMenuItem_1 = new JMenuItem("Save");
        mntmNewMenuItem_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    save();
                    }
                catch (Exception e1) {
                    e1.printStackTrace();
                    }
                }
        });
        mnNewMenu.add(mntmNewMenuItem_1);   

        JMenuItem mntmNewMenuItem_2 = new JMenuItem("Exit");
        mntmNewMenuItem_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        mnNewMenu.add(mntmNewMenuItem_2);

        //New list "Left" and properties
        final JList leftlist = new JList();
        leftlist.setBounds(0, 37, 161, 464);
        frame.getContentPane().add(leftlist);
        leftlist.setModel(new AbstractListModel() {
            String[] values = new String[] {"Case", "Motherboard", "CPU", "GPU", "PSU", "RAM", "HDD"};
            public int getSize() {
                return values.length;
                }
            public Object getElementAt(int index) {
                return values[index];
                    }
                });

        //right list
        final JList rightlist = new JList();
        rightlist.setBounds(412, 37, 161, 464); 
        frame.getContentPane().add(rightlist);

        //add button
        JButton btnNewButton = new JButton("Add");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                list.addElement(leftlist.getSelectedValue());
                rightlist.setModel(list);
            }
        });
        btnNewButton.setBounds(231, 167, 131, 31);
        frame.getContentPane().add(btnNewButton);

        //remove button
        JButton btnNewButton_1 = new JButton("Remove")  ;
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                list.removeElement(rightlist.getSelectedValue());
                rightlist.setModel(list);
            }
        });
        btnNewButton_1.setBounds(231, 273, 131, 31);
        frame.getContentPane().add(btnNewButton_1);
    }

    final DefaultListModel list = new DefaultListModel();

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

    public void load(){
        try {
            File file = new File("save.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Configuration model = (Configuration) jaxbUnmarshaller.unmarshal(file);  
            //System.out.println(model.getComponent());

            list.clear();

            list.addElement(model.getComponent());

            System.out.println(list);
            System.out.println(list.get(0));

        } 
        catch (JAXBException exp) {
            exp.printStackTrace();
            }
        }
}`

这里是注释代码:

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlAccessType;

@XmlRootElement(name = "Configuration")
public class Configuration {

    @XmlElement
    protected List<String> component;

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

编组工作正常,没有任何问题,但是当我尝试解组它时会出现问题。

问题#1:在新运行中加载时,右侧列表不会显示。它只会在我按下添加/删除按钮后显示。我相信它,因为rightlist.setModel(list);在我做之前不会被调用。

问题#2:在解组XML文件之后,输出看起来像在数组中并显示为数组而不是单个元素 ex([GPU,HDD,主板] 当我在寻找:GPU

HDD

主板

非常感谢任何解决这些问题的帮助!

0 个答案:

没有答案