Consider this example -
I have a class called Report that has a field of type Message. The Message class has a body field, which is a string. A body can be any string, but sometimes it contains properly formatted XML content . How can I make sure that when the "body" contains XML content, serialization takes the form of an XML structure, rather than what it currently provides?
Here is the exit code -
Report class
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "Report") @XmlType(propOrder = { "message"}) public class Report { private Message message; public Message getMessage() { return message; } public void setMessage(Message m) { message = m; } }
Post class
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; @XmlType(propOrder = { "body" }) public class Message { private String body; public String getBody() { return body; } @XmlElement public void setBody(String body) { this.body = body; } }
home
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class SerializationTest { public static void main(String args[]) throws Exception { JAXBContext jaxbContext = JAXBContext.newInstance(Report.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Report report = new Report(); Message message = new Message(); message.setBody("Sample report message."); report.setMessage(message); jaxbMarshaller.marshal(report, System.out); message.setBody("<rootTag><body>All systems online.</body></rootTag>"); report.setMessage(message); jaxbMarshaller.marshal(report, System.out); } }
The output is as follows:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Report> <message> <body>Sample report message.</body> </message> </Report> <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Report> <message> <body><rootTag><body>All systems online.</body></rootTag></body> </message> </Report>
As can be seen from the above, for the second instance of "body" the serialization performed
<body><rootTag><body>All systems online.</body></rootTag></body>
instead
<body><rootTag><body>All systems online.</body></rootTag></body>
How to solve this problem?
source share