java - 使用 jaxb 将 java 对象转换为 xml,反之亦然(marshal 和 unmarshal)

标签 java xml swing jaxb marshalling

我假设有一个名为 save() 的方法,该方法应将右侧面板中的计算机部件列表编码(marshal)到 XML 文件中。相反,另一个名为 load() 的方法应该将保存的 XML 文件解码回对象。

基本上,“Save”事件将调用 save() 方法并将右侧面板中的部件列表保存到 XML 文件中。 “Load”事件应该清除右侧面板,并调用 load() 方法。

当调用load()时,它应该在右侧面板中显示未编码的数据。我让“退出”开始工作。

不过,我很难弄清楚“加载”和“保存”部分。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class PCParts implements ActionListener{

    JList destinationList, sourceList;
    JButton buttonin, buttonout;

    DefaultListModel source, destination;

    public JPanel createContentPane (){

        JPanel totalGUI = new JPanel();

        source = new DefaultListModel();
        destination = new DefaultListModel();

        String shoppingItems[] = {"Case", "Motherboard", "CPU", "RAM", "GPU",
        "HDD", "PSU"};

        for(int i = 0; i < shoppingItems.length; i++)
        {
            source.addElement(shoppingItems[i]);
        }

        destinationList = new JList(source);
        destinationList.setVisibleRowCount(10);
        destinationList.setFixedCellHeight(20);
        destinationList.setFixedCellWidth(140);
        destinationList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        JScrollPane list1 = new JScrollPane(destinationList);

        sourceList = new JList(destination);
        sourceList.setVisibleRowCount(10);
        sourceList.setFixedCellHeight(20);
        sourceList.setFixedCellWidth(140);
        sourceList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        JScrollPane list2 = new JScrollPane(sourceList);

        JPanel buttonPanel = new JPanel();

        buttonin = new JButton(">>");
        buttonin.setHorizontalAlignment(SwingConstants.RIGHT);
        buttonin.addActionListener(this);
        buttonPanel.add(buttonin);

        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));

        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
        bottomPanel.add(list1);
        bottomPanel.add(Box.createRigidArea(new Dimension(5,0)));
        bottomPanel.add(buttonPanel);

                buttonout = new JButton("<<");
                buttonout.addActionListener(this);
                buttonPanel.add(buttonout);
        bottomPanel.add(Box.createRigidArea(new Dimension(5,0)));
        bottomPanel.add(list2);
        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));

        totalGUI.add(bottomPanel);
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    private JPanel createSquareJPanel(Color color, int size) {
        JPanel tempPanel = new JPanel();
        tempPanel.setBackground(color);
        tempPanel.setMinimumSize(new Dimension(size, size));
        tempPanel.setMaximumSize(new Dimension(size, size));
        tempPanel.setPreferredSize(new Dimension(size, size));
        return tempPanel;
    }

    public void actionPerformed(ActionEvent e) 
    {
        int i = 0;


        if(e.getSource() == buttonin)
        {
            int[] fromindex = destinationList.getSelectedIndices();
            Object[] from = destinationList.getSelectedValues();

            for(i = 0; i < from.length; i++)
            {
                destination.addElement(from[i]);
            }

            for(i = (fromindex.length-1); i >=0; i--)
            {
                source.remove(fromindex[i]);
            }
        }

        else if(e.getSource() == buttonout)
        {
            Object[] to = sourceList.getSelectedValues();
            int[] toindex = sourceList.getSelectedIndices();

            for(i = 0; i < to.length; i++)
            {
                source.addElement(to[i]);
            }

            for(i = (toindex.length-1); i >=0; i--)
            {
                destination.remove(toindex[i]);
            }
        }
    }



    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("PC Parts Builder");
        JMenu file = new JMenu ("File");
        file.setMnemonic (KeyEvent.VK_F);

        PCParts demo = new PCParts();
        frame.setContentPane(demo.createContentPane());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

        JMenuBar menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);

        JMenu mnFile = new JMenu("File");
        menuBar.add(mnFile);

        JMenuItem item;
        file.add(item = new JMenuItem("Load"));
        item.setMnemonic (KeyEvent.VK_O);
        item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                doOpenCommand();
            }

            private void doOpenCommand() {
                // TODO Auto-generated method stub

            }


        });

        mnFile.add(item);


        JMenuItem mntmSave = new JMenuItem("Save");
        mntmSave.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                doSaveCommand();

            }

            private void doSaveCommand() {

            }
        });
        mnFile.add(mntmSave);

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

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

最佳答案

只需创建一个类 Parts持有List<String> 。然后您只需编码/解码到该类的实例。

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Parts {

    @XmlElement(name = "part")
    private List<String> part;

    public List<String> getPart() { return part; }
    public void setPart(List<String> part) { this.part = part; }
}

对于编码(保存),您将创建一个 Marshaller通过创建 JAXBContext使用Parts类(class)。只需调用marshal在编码器上。

See some of the overloaded marshal methods (通知File)

private void doSaveCommand() throws Exception {
    ArrayList<String> save = new ArrayList<>();
    for (int i = 0; i < destination.size(); i++) {
        save.add((String)destination.getElementAt(i));
    }
    Parts parts = new Parts();
    parts.setPart(save);
    JAXBContext context = JAXBContext.newInstance(Parts.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(parts, System.out);
}

请注意,您遇到了一些设计问题。 DefaultListModels需要访问的,不能是因为监听器代码位于 static 中上下文和模型不是 static 。我刚做了模型static让它工作,但你需要重新设计你的代码。这是结果(到标准输出 - 您将编码到文件)。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parts>
    <part>Case</part>
    <part>Motherboard</part>
    <part>CPU</part>
</parts>

我会让你自己进行解码工作。这应该可以帮助您入门。

一些资源

关于java - 使用 jaxb 将 java 对象转换为 xml,反之亦然(marshal 和 unmarshal),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26797838/

相关文章:

java - 行选择后 JTable 更新

java - 如何获取 HTML 文档中的 html 标签

c# - 连同数据一起序列化 XmlDoc 注释

xml - 当匹配某个属性的值时,将一个完整的元素复制到新的 XML,并使用 XSLT 更改内部另一个属性的值

java - tomcat 将它被指示读取的文件保存在哪里?

Java Swing - 在 JPanel 中获取源代码

java - 连接按钮不起作用

java - Matrix.solve() 使用 RationalFunction 给出的答案与使用 Rational 给出的答案不同

java - 验证用户输入 - 仅字符

java - 删除单个链表上的节点的最有效方法?