Results 1 to 2 of 2
  1. #1
    Java Tip's Avatar
    Java Tip is offline Moderator
    Join Date
    Nov 2007
    Posts
    1,694
    Blog Entries
    430
    Rep Power
    9

    Default How to extracts a java bean object from the XML file

    This tip will show the way to read the xml file and extract the bean from it using XMLDecoder.

    In this example object of the java bean MyBean will be extracted from the MyXML.xml file.

    Class of the Java Bean: MyBean.java

    Java Code:
    public class MyBean {
    	private String name = null;
    	private int age;
    	public int getAge() {
    		return age;
    	}
    	public void setAge(int age) {
    		this.age = age;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    }
    Java class that extracts a java object from the XML: BeanToXMLExp.java

    Java Code:
    import java.beans.XMLDecoder;
    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    
    public class XMLToBeanExp {
    	public static void main(String[] args) {
    		try {
    			XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(
    					new FileInputStream("C:\\MyXML.xml")));
    			MyBean myBean = (MyBean) decoder.readObject();
    			decoder.close();
    			System.out.println(myBean.getAge());
    			System.out.println(myBean.getName());
    
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }

  2. #2
    Join Date
    Jan 2009
    Posts
    3
    Rep Power
    0

Similar Threads

  1. Replies: 2
    Last Post: 11-26-2010, 02:12 AM
  2. Replies: 1
    Last Post: 01-29-2009, 09:35 AM
  3. Creating a File object in Servlet
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-16-2008, 10:24 AM
  4. Initializing property object from a file
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-29-2007, 04:55 PM
  5. Replies: 1
    Last Post: 05-20-2007, 08:52 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •