Java 是否可以强制JAXB在XML标记中封装非法字符?
我有一个充满对象的数据库,还有用户定义的属性。例如:Java 是否可以强制JAXB在XML标记中封装非法字符?,java,xml,jaxb,Java,Xml,Jaxb,我有一个充满对象的数据库,还有用户定义的属性。例如: class Media { String name; String duration; Map<String,String> custom_tags; } Media: Name: day_at_the_beach.mp4 Length: 4:22 Custom Tags: Videographer: Charles Owner ID #: 17a 但是,我需要返回前一个无效的XML,
class Media {
String name;
String duration;
Map<String,String> custom_tags;
}
Media:
Name: day_at_the_beach.mp4
Length: 4:22
Custom Tags:
Videographer: Charles
Owner ID #: 17a
但是,我需要返回前一个无效的XML,以维护前一个不太挑剔的代码实现的遗留行为。有没有办法告诉JAXB不要担心非法的XML字符,或者我会在编码之前/之后执行字符串替换?我目前的实施方式很简单:
public static <T> String toXml(Object o, Class<T> z) {
try {
StringWriter sw = new StringWriter();
JAXBContext context = JAXBContext.newInstance(z);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(o, sw);
return sw.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
公共静态字符串toXml(对象o,类z){
试一试{
StringWriter sw=新的StringWriter();
JAXBContext context=JAXBContext.newInstance(z);
Marshaller=context.createMarshaller();
元帅,元帅(o,sw);
返回sw.toString();
}捕获(JAXBEException e){
抛出新的运行时异常(e);
}
}
我为这个特定对象构建了一个XmlAdapter,然后:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
document.setStrictErrorChecking(false); // <--- This one. This accomplished it.
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document Document=db.newDocument();
文件。设置TrictErrorChecking(假)//
public static <T> String toXml(Object o, Class<T> z) {
try {
StringWriter sw = new StringWriter();
JAXBContext context = JAXBContext.newInstance(z);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(o, sw);
return sw.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
document.setStrictErrorChecking(false); // <--- This one. This accomplished it.