How can I use the below code to unmarshal a XML string an map it to the JAXB object below?
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
U
Or if you want a simple one-liner:
Person person = JAXB.unmarshal(new StringReader("<?xml ..."), Person.class);
To pass XML content, you need to wrap the content in a Reader
, and unmarshal that instead:
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("xml string here");
Person person = (Person) unmarshaller.unmarshal(reader);
If you already have the xml, and comes more than one attribute, you can handle it as follows:
String output = "<ciudads><ciudad><idCiudad>1</idCiudad>
<nomCiudad>BOGOTA</nomCiudad></ciudad><ciudad><idCiudad>6</idCiudad>
<nomCiudad>Pereira</nomCiudad></ciudads>";
DocumentBuilder db = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));
Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
.getElementsByTagName("ciudad");
for (int i = 0; i < nodes.getLength(); i++) {
Ciudad ciudad = new Ciudad();
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("idCiudad");
Element element2 = (Element) name.item(0);
ciudad.setIdCiudad(Integer
.valueOf(getCharacterDataFromElement(element2)));
NodeList title = element.getElementsByTagName("nomCiudad");
element2 = (Element) title.item(0);
ciudad.setNombre(getCharacterDataFromElement(element2));
ciudades.getPartnerAccount().add(ciudad);
}
}
for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}
the method getCharacterDataFromElement is
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
There is no unmarshal(String)
method. You should use a Reader
:
Person person = (Person) unmarshaller.unmarshal(new StringReader("xml string"));
But usually you are getting that string from somewhere, for example a file. If that's the case, better pass the FileReader
itself.
If you want to parse using InputStreams
public Object xmlToObject(String xmlDataString) {
Object converted = null;
try {
JAXBContext jc = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
converted = unmarshaller.unmarshal(stream);
} catch (JAXBException e) {
e.printStackTrace();
}
return converted;
}