简体   繁体   English

使用jaxb将Java对象转换为xml,反之亦然(将其转换为元组和非元组)

[英]convert java object using jaxb to xml and vice versa (marshal and unmarshal)

I am suppose to have a method called save() which should marshal the list of computer parts in the right panel to an XML file. 我想有一个名为save()的方法,该方法应将右侧面板中的计算机部件列表整理为XML文件。 In reverse, another method called load() that should unmarshal the saved XML file back into an object. 相反,另一种称为load()方法应将已保存的XML文件解组到对象中。

So basically, the "Save" event will call save() method and save the list of parts in the right panel to an XML file. 因此,基本上,“保存”事件将调用save()方法并将右侧面板中的零件列表保存到XML文件。 The "Load" event should clear the right panel, and call load() method. “ Load”事件应清除右侧面板,并调用load()方法。

When load() is called, it should display the unmarshalled data in the right panel. 调用load() ,应在右侧面板中显示未整理的数据。 I got "Exit" to work. 我有“出口”上班。

I'm having hard time figuring out the "Load" and "Save" parts though. 不过,我很难弄清楚“加载”和“保存”部分。

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

Just create a class Parts to hold a List<String> . 只需创建一个类Parts来保存List<String> Then you can just marshal/unmarshal to an instance of that class. 然后,您可以编组/解组该类的实例。

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

As for the marshalling (save), you would create a Marshaller by creating a JAXBContext using the Parts class. 至于编组(保存),您可以通过使用Parts类创建JAXBContext来创建Marshaller The just call marshal on the marshaller. marshal上的正义呼唤。

See some of the overloaded marshal methods (notice File ) 请参见一些重载的marshal方法 (请注意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);
}

Note you have a little design problem. 请注意,您有一些设计问题。 The DefaultListModels that need to be accessed, can't be because the listener code is in a static context, and models are not static . 不需要访问的DefaultListModels不能是因为侦听器代码在static上下文中,并且模型不是static I just made the models static to get it to work, but you'll want to redesign your code a bit. 我只是使模型static以使其正常工作,但您需要稍微重新设计代码。 Here is the result (to standard output - you will to marshal to file). 这是结果(对于标准输出,您将打包存档)。

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

I'll let you work on the unmarshalling on your own. 我会让您自己进行编组工作。 This should get you started. 这应该使您入门。

Some Resource 一些资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM