An Interest In:
Web News this Week
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
August 29, 2022 12:30 pm GMT
Original Link: https://dev.to/codever/how-to-unmarshall-xml-string-to-java-object-with-jaxb-1oif
How to unmarshall xml string to java object with JAXB
Given the following Superhero
class:
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 lombok.Getter;import lombok.Setter;@XmlRootElement(name = "super-hero")@XmlAccessorType(XmlAccessType.FIELD)@Getter@Setterclass SuperHero { @XmlElement(name = "name") String name; @XmlElement(name = "super-power") String superPower;}
You can convert an XML String to a SuperHero
instance with the following code:
import static org.junit.jupiter.api.Assertions.assertEquals;import java.io.StringReader;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Unmarshaller;import org.junit.jupiter.api.Test;import org.junit.platform.runner.JUnitPlatform;import org.junit.runner.RunWith;@RunWith(JUnitPlatform.class)class TestXmlStringToObjectUnmarshalling { static final String superHeroXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<super-hero>" + " <name>Superman</name>" + " <super-power>Flight</super-power>" + "</super-hero>"; @Test void testXmlUnmarshalling() throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(SuperHero.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); StringReader reader = new StringReader(superHeroXml); SuperHero superHero = (SuperHero) unmarshaller.unmarshal(reader); assertEquals("Flight", superHero.getSuperPower()); }}
Note:
- create a
JAXBContext
which includes theSuperHero
class -JAXBContext.newInstance(SuperHero.class)
- create a JAXB
Unmarshaller
and apply theunmarshal
method to aStringReader
wrapping the text (it could be also aFileReader
or any otherReader
for that matter)
Shared with from Codever. Use copy to mine functionality to add it to your personal snippets collection.
Original Link: https://dev.to/codever/how-to-unmarshall-xml-string-to-java-object-with-jaxb-1oif
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To