この例を考えてみましょう -
タイプ Message のフィールドを持つ Report というクラスがあります。Message クラスには、文字列である「body」というフィールドがあります。「本文」には任意の文字列を指定できますが、適切にフォーマットされた XML コンテンツが含まれている場合があります。「本文」に XML コンテンツが含まれている場合、シリアライゼーションが現在提供されているものではなく、XML 構造の形式をとるようにするにはどうすればよいですか?
出力付きのコードは次のとおりです-
レポートクラス
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; }
}
メッセージクラス
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; }
}
主要
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);
}
}
出力は次のとおりです-
<?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>
上記の出力からわかるように、「body」の 2 番目のインスタンスでは、シリアライゼーションが生成されます。
<body><rootTag><body>All systems online.</body></rootTag></body>
それ以外の
<body><rootTag><body>All systems online.</body></rootTag></body>
この問題を解決するには?