Skip to content

Instantly share code, notes, and snippets.

@dmikurube
Created March 17, 2015 13:30
Show Gist options
  • Save dmikurube/aeaef5e012e8c8afa3b4 to your computer and use it in GitHub Desktop.
Save dmikurube/aeaef5e012e8c8afa3b4 to your computer and use it in GitHub Desktop.
JAXB Adapter from DOM nodes / elements
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
// XmlAdapter<Object,*> receives XML DOM nodes in org.w3c.dom.Element.
public class MyXmlAdapter extends XmlAdapter<Object, TargetClass> {
private DocumentBuilder documentBuilder;
public MyXmlAdapter() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
documentBuilder = factory.newDocumentBuilder();
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public TargetClass unmarshal(Object nodes) {
Element element = (Element)nodes;
TargetClass target = new TargetClass(...);
// target....
return target;
}
@Override
public Object marshal(TargetClass v) {
Document document = documentBuilder.newDocument();
Element root = document.createElement("element");
// element....
return root;
}
}
@dmikurube
Copy link
Author

XmlAdapter<org.w3c.dom.Element, *> does work well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment