Creating an xml file from a java object

  • I want to create an XML file from java 6 (this is the first time I want to try it), and I would like to give an example of how to do this with the DOM. I need an example showing how to build a tree?
  • Is it possible to create an EDMX file from a java object?

Regards, Boris

+4
source share
3 answers

The simplest example of converting a java object to xml is the following:

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

Prints the following to the console:

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

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

Good luck

0
source

I think you should go with JAXB and JAXP , it will make your life much easier than using the DOM .....

0
source

Source: https://habr.com/ru/post/1433634/


All Articles