java如何使用JAXB对有时包含XML内容,有时不包含XML内容的字符串进行整理?
考虑这个例子-
我有一个名为Report的类,它有一个Message类型的字段。消息类有一个名为“body”的字段,它是一个字符串。“body”可以是任何字符串,但有时它包含格式正确的XML内容。如何确保当“body”包含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”的第二个实例,产生了序列化
<body><rootTag><body>All systems online.</body></rootTag></body>
而不是
<body><rootTag><body>All systems online.</body></rootTag></body>
如何解决这个问题
# 1 楼答案
3种不同的解决方案1)、2)3),如下所示:
1)以下帖子是对您的解决方案Loresh的描述:
http://anna-safronova.livejournal.com/2524.html?thread=9180
这仍然缺少详细信息
对于Embeded html,我们需要一个
<![CDATA
块JAXB的依赖性
com。太阳xml。绑定马歇尔。角色逃逸者
需要导入jaxb impl进行编译/执行,例如
2)另一种类似的方法是JDK的rt.jar依赖性
com。太阳xml。内部的绑定角色逃逸者
http://theopentutorials.com/tutorials/java/jaxb/jaxb-marshalling-and-unmarshalling-cdata-block/
同样的限制/依赖于目标JDK,Eclipse/Maven上的一些调整也是必要的(糟糕的选择/我的意见)
3)最后,在Reg Whitton的另一篇文章中找到了最佳解决方案:
https://stackoverflow.com/a/12637295/560410
这是详细的接收:
http://javacoalface.blogspot.co.uk/2012/09/outputting-cdata-sections-with-jaxb.html
这对我来说太完美了
# 2 楼答案
如果仅用于编组,则忽略<;及;, 我们可以使用以下方法:
# 3 楼答案
注意:我是EclipseLink JAXB (MOXy)领导和JAXB (JSR-222)专家组成员
使用
@XmlAnyElement
注释并指定DOMHandler
来映射此用例。在使用JAXB RI执行此操作时,似乎存在错误,但以下用例适用于EclipseLink JAXB(MOXy)BodyDomainHandler
默认情况下,JAXB实现将未映射的内容表示为DOM节点。您可以利用
DomHandler
作为DOM的替代表示,在本例中,我们将DOM表示为String
消息
下面是如何在
Message
类上指定@XmlAnyElement
注释输出
下面是运行
SerialziationTest
的输出:了解更多信息
注意-JAXB RI中的Bug
JAXB参考实现中似乎有一个bug,示例代码将产生如下堆栈跟踪: