Last active
March 24, 2022 09:02
-
-
Save team172011/385b4b520a4dca299e23f9a968054d1e to your computer and use it in GitHub Desktop.
XmlAdapter for String to XML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.io.StringReader; | |
import java.io.StringWriter; | |
import javax.xml.bind.JAXBContext; | |
import javax.xml.bind.JAXBException; | |
import javax.xml.parsers.DocumentBuilderFactory; | |
import javax.xml.parsers.ParserConfigurationException; | |
import org.w3c.dom.Document; | |
public class XmlAdapter { | |
private final Class clazz; | |
public XmlAdapter(final Class clazz) { | |
this.clazz = clazz; | |
} | |
public String toXml(final Object o) { | |
try (StringWriter sw = new StringWriter()) { | |
final JAXBContext jbc = JAXBContext.newInstance(this.clazz); | |
jbc.createMarshaller().marshal(o, sw); | |
return sw.toString(); | |
} catch (final JAXBException | IOException e) { | |
throw new IllegalStateException(e); | |
} | |
} | |
public Document toDom(final Object o) { | |
try { | |
final Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); | |
final JAXBContext jbc = JAXBContext.newInstance(this.clazz); | |
jbc.createMarshaller().marshal(o, d); | |
return d; | |
} catch (final JAXBException | ParserConfigurationException e) { | |
throw new IllegalStateException(e); | |
} | |
} | |
public Object toObject(final String xml) { | |
try (StringReader sr = new StringReader(xml)) { | |
final JAXBContext jbc = JAXBContext.newInstance(this.clazz); | |
return jbc.createUnmarshaller().unmarshal(sr); | |
} catch (final JAXBException e) { | |
throw new IllegalStateException(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment