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 write a java bean class object to XML file

    This tip will show the way to convert the java bean file to the xml file using the XMLEncoder.

    In this example object of the java bean MyBean will be written to 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 writes a java object to the XML: BeanToXMLExp.java

    Java Code:
    import java.beans.XMLEncoder;
    import java.io.BufferedOutputStream;
    import java.io.FileOutputStream;
    public class BeanToXMLExp {
    	public static void main(String[] args) {
    		try {
    			MyBean myBean = new MyBean();
    			myBean.setName("Tom");
    			myBean.setAge(28);
    			XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
    					new FileOutputStream("C:\\MyXML.xml")));
    			encoder.writeObject(myBean);
    			encoder.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }

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

    Default

    hi i am new to the j2ee please help me, how to gain the knowledge regarding j2ee


    thanx.

Similar Threads

  1. Replies: 1
    Last Post: 01-29-2009, 09:33 AM
  2. Replies: 4
    Last Post: 03-25-2008, 12:16 PM
  3. Help with write file in java
    By mathias in forum New To Java
    Replies: 1
    Last Post: 07-31-2007, 06:51 PM
  4. About bean:write
    By yuchuang in forum Web Frameworks
    Replies: 1
    Last Post: 04-30-2007, 03:31 PM
  5. Struts tag error with bean:write
    By sandor in forum Web Frameworks
    Replies: 1
    Last Post: 04-07-2007, 04:50 AM

Posting Permissions

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