Boris Mandovskes
Boris Mandovskes

Reputation: 111

Create xml file from java object

  1. I want to create an XML file from java 6 (it's the first time I want to try that) and I would like an example of how can I do that with DOM. I need an example showing how to build tree?
  2. Can I create an EDMX file from a java object ?

Regards, Boris

Upvotes: 4

Views: 7206

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

It think you should go with JAXB and JAXP, this will make your life much easier than using DOM.....

Upvotes: 0

michael
michael

Reputation: 185

Simplest example of convert java object to xml is this:

@XmlRootElement( name = "entity")
public class Entity {

    private int age = 22;
    private String firstname = "Michael";

    public int getAge() {
        return age;
    }

    public void setAge( int age ) {
        this.age = age;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname( String firstname ) {
        this.firstname = firstname;
    }
}

public class Main {
    public static void main( String[] args ) {
        JAXBContext jc = JAXBContext.newInstance( Entity.class );
        Marshaller m = jc.createMarshaller();
        m.marshal( new Entity(), System.out );
    } 
}

Will print to the console this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><entity><age>22</age><firstname>Michael</firstname></entity>

Upvotes: 6

aviad
aviad

Reputation: 8278

If you need to serialize java objects to XML file - just feed them to XStream ! It works both ways. Code snippets here .

Good luck!

Upvotes: 0

Related Questions