简体   繁体   中英

Java serialized bean to xml

How can i convert a Java Bean in a simple XML. I need a standard methed for alla object.

For example:

public Class Customers {
    public Class Person {
        private String name;

        public String getName() {
            return this.name;
        }
        public String setName(newName) {
            this.name = newName;
        }
    } //end Person class

    public String getPerson() {
         return this.Person;
    }
    public String setName(newPerson) {
        this.Person = newPerson;
    }
} //end Customers class

Instantiate by:

Customers customers = new Customers();
Person person = new Person();
person.setName("Siegfried");
customers.setPerson(person);

System.out.print(beanToXml(customers));

Xml Output:

<Customers>
    <Person>
        <name>Siegfried</name>
    </Person>
</Customers>

you can use JAXB for this, this is the perfect use case, all you need to do is annotate your bean.

Example here

You can use third party like XStream .It allows to save object to , and it does not need that object must be Serializable . We had similair problem in our company (class that cannot be modified and must be saved) and XStream helped us. Please look at: http://x-stream.github.io/tutorial.html for simple tutorial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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