Skip to content

Instantly share code, notes, and snippets.

@xSAVIKx
Created March 20, 2017 21:10
Show Gist options
  • Save xSAVIKx/de8fd09a56bdab3a26c3a232016b6112 to your computer and use it in GitHub Desktop.
Save xSAVIKx/de8fd09a56bdab3a26c3a232016b6112 to your computer and use it in GitHub Desktop.
JAXB Unmarshalling from Source example
import javax.xml.bind.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Demo {
public static void main(String[] args) throws JAXBException, IOException {
JAXBContext context = JAXBContext.newInstance(Type.class, InnerType.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Type type = new Type();
type.setId("id");
InnerType value = new InnerType("Pretty Value");
type.setValue(value);
File output = new File("type.xml");
System.out.println(type);
marshaller.marshal(type, output);
Unmarshaller unmarshaller = context.createUnmarshaller();
try (FileInputStream fis = new FileInputStream(output)) {
Source source = new StreamSource(fis);
JAXBElement<Type> element = unmarshaller.unmarshal(source, Type.class);
Type typeFromXml = element.getValue();
System.out.println(typeFromXml);
}
}
}
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class InnerType {
private String value;
public InnerType() {
}
public InnerType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("InnerType{");
sb.append("value='").append(value).append('\'');
sb.append('}');
return sb.toString();
}
}
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class InnerTypeAdapter extends XmlAdapter<String, InnerType> {
@Override
public InnerType unmarshal(String v) throws Exception {
return new InnerType(v);
}
@Override
public String marshal(InnerType v) throws Exception {
return v.getValue();
}
}
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Type {
@XmlElement
private String id;
@XmlJavaTypeAdapter(InnerTypeAdapter.class)
@XmlElement
private InnerType value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public InnerType getValue() {
return value;
}
public void setValue(InnerType value) {
this.value = value;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Type{");
sb.append("id='").append(id).append('\'');
sb.append(", value=").append(value);
sb.append('}');
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment