<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <group> <name> a group </name> <user> <name> user 1</name> <password> pass 1</password> </user> <user> <name> user 2</name> <password> pass 2</password> </user> </group>
To bind this xml to an object, we create 2 classes:
1. Group.java
package com.lapth82.jaxb.bean; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "group") public class Group { private String groupName; private List2. User.javalstUser; @XmlElement(name = "user") public List getLstUser() { return lstUser; } public void setLstUser(List lstUser) { this.lstUser = lstUser; } @XmlElement(name = "name") public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } }
package com.lapth82.jaxb.bean; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "user") public class User { private String userName; private String password; @XmlElement(name = "name") public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @XmlElement(name = "password") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Write a short code to test:
package com.lapth82.jaxb.test; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import com.lapth82.jaxb.bean.Group; public class TestJAXB { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Group.class); Unmarshaller unMarshaller = jc.createUnmarshaller(); Group group = (Group) unMarshaller.unmarshal(new File("xml/sample.xml")); group.getLstUser().get(1).setUserName("My Name"); group.getLstUser().get(1).setPassword("My password"); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(group, System.out); } }
The result:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<group>
<name> a group </name>
<user>
<password> pass 1</password>
<name> user 1</name>
</user>
<user>
<password>My password</password>
<name>My Name</name>
</user>
</group>
For the demonstration, please download Source code from my repository on Github
No comments:
Post a Comment