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

后端 未结 1 749
日久生厌
日久生厌 2021-01-22 08:52

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. In reverse, another method called

相关标签:
1条回答
  • 2021-01-22 09:35

    Just create a class Parts to hold a 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. The just call marshal on the marshaller.

    See some of the overloaded marshal methods (notice 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. I just made the models static to get it to work, but you'll want to redesign your code a bit. 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

    • Marshaller API doc has some examples
    • Unmarshaller API doc has some examples
    • JAXContext API doc has some explanation about the context
    • General JAXB tutorial
    0 讨论(0)
提交回复
热议问题