Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: How to parse an object to and from XML using JAXB

  1. #1
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default How to parse an object to and from XML using JAXB

    I think your question makes this sound harder than it actually is. If I understand correctly you wish to store or serialize a Java object to an XML document?

    You can of course go through the object members and store this XML your self somehow or you could look into something like JAXB which can transform Java objects to XML and XML to Java objects.

    For more information on JAXB and how to get the appropriate libraries head over to https://jaxb.dev.java.net/

    Here is a code snippet to transform an object into XML and back.

    import java.io.StringReader;
    import java.io.StringWriter;
     
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;
    import javax.xml.bind.annotation.XmlRootElement;
     
    public class JaxbTest1 {
        public static void main(String[] args) throws Throwable {
            // =============================================================================================================
            // Setup JAXB
            // =============================================================================================================
     
            // Create a JAXB context passing in the class of the object we want to marshal/unmarshal
            final JAXBContext context = JAXBContext.newInstance(JavaObject.class);
     
            // =============================================================================================================
            // Marshalling OBJECT to XML
            // =============================================================================================================
     
            // Create the marshaller, this is the nifty little thing that will actually transform the object into XML
            final Marshaller marshaller = context.createMarshaller();
     
            // Create a stringWriter to hold the XML
            final StringWriter stringWriter = new StringWriter();
     
            // Create the sample object we wish to transform into XML
            final JavaObject javaObject = new JavaObject();
            javaObject.setName("Json");
            javaObject.setRole("Moderator");
            javaObject.setAge(28);
     
            // Marshal the javaObject and write the XML to the stringWriter
            marshaller.marshal(javaObject, stringWriter);
     
            // Print out the contents of the stringWriter
            System.out.println(stringWriter.toString());
     
            // =============================================================================================================
            // Unmarshalling XML to OBJECT
            // =============================================================================================================
     
            // Create the unmarshaller, this is the nifty little thing that will actually transform the XML back into an object
            final Unmarshaller unmarshaller = context.createUnmarshaller();
     
            // Unmarshal the XML in the stringWriter back into an object
            final JavaObject javaObject2 = (JavaObject) unmarshaller.unmarshal(new StringReader(stringWriter.toString()));
     
            // Print out the contents of the JavaObject we just unmarshalled from the XML
            System.out.println(javaObject2.toString());
        }
     
        /**
         * JavaObject is the sample object we've created to use for marshalling to and from XML.
         * Make sure you have the @XmlRootElement annotation at the top there as well or JAXB
         * might moan.
         */
        @XmlRootElement
        private static class JavaObject {
     
            private String name;
     
            private String role;
     
            private int age;
     
            public JavaObject() {
     
            }
     
            public String getName() {
                return name;
            }
     
            public void setName(String name) {
                this.name = name;
            }
     
            public String getRole() {
                return role;
            }
     
            public void setRole(String role) {
                this.role = role;
            }
     
            public int getAge() {
                return age;
            }
     
            public void setAge(int age) {
                this.age = age;
            }
     
            @Override
            public String toString() {
                return "Name [" + this.name + "], Role [" + this.role + "], Age [" + this.age + "]";
            }
        }
    }

    Enjoy!

    // Json

  2. The Following User Says Thank You to Json For This Useful Post:

    Mr.777 (August 8th, 2013)


  3. #2
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: How to parse an object to and from XML using JAXB

    This has really saved my day today. Thanks man.
    Anyone who stops learning is old, whether at twenty or eighty. Anyone who keeps learning stays young. The greatest thing in life is to keep your mind young.

    - Henry Ford

Similar Threads

  1. object not accessible
    By sheikhms60 in forum Object Oriented Programming
    Replies: 1
    Last Post: February 22nd, 2010, 07:37 PM
  2. Class and Object
    By jyothishey in forum Object Oriented Programming
    Replies: 2
    Last Post: January 25th, 2010, 08:48 AM
  3. Object o = new Object(); need help
    By zeeshanmirza in forum Object Oriented Programming
    Replies: 11
    Last Post: January 6th, 2010, 10:01 PM
  4. Object Injection
    By Json in forum Java Programming Tutorials
    Replies: 1
    Last Post: December 4th, 2009, 04:08 AM
  5. How to read an XML document in Java with DOM Parse?
    By JavaPF in forum File Input/Output Tutorials
    Replies: 0
    Last Post: May 20th, 2008, 07:04 AM