JAXB - Avoid converting ( into < and ) into > during Marshalling
In this article, let us see how to avoid converting < to < ; and > to > ; and & to & ; during JAXB Marshalling operation.
1. CharacterEscapeHandler creation
Create a custom Escape Handler by implementing the CharacterEscapeHandler interface as given below.
public class JaxbCharacterEscapeHandler implementsCharacterEscapeHandler {
public void escape(char[] buf, int start, int len, booleanisAttValue,
Writer out) throws IOException {
for (int i = start; i < start + len; i++) {
char ch = buf[i];
out.write(ch);
}
}
}
2. Marshaller Code
Use the below code snippet for JAXB Marshalling operation.
Note: Please go through the basics of using JAXB Marshalling code samples before using this example
import java.io.IOException;import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
import com.sun.xml.bind.marshaller.DataWriter;
public class JaxbMarshaller {
public static void main(String[] args) {
// Note: Provide input for the below objects
Object jaxbObject = null; // Create the right Input object
String packageName = jaxbObject.getClass().getPackage().getName(); // Provide the package name of the generated classes
try {
JAXBContext jaxbContext = JAXBContext.newInstance(packageName);
Marshaller marshaller = jaxbContext.createMarshaller();
// Set UTF-8 Encoding
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
// The below code will take care of avoiding the conversion of < to < and > to > etc
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
DataWriter dataWriter = new DataWriter(printWriter, "UTF-8", new JaxbCharacterEscapeHandler());
// Perform Marshalling operation
marshaller.marshal(jaxbObject, dataWriter);
System.out.println(stringWriter.toString());
} catch (JAXBException e) {
System.err.println("Error in marshalling...");
}
}
} or 直接设置属性:marshaller.setProperty("com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler",
new CharacterEscapeHandler() {
@Override
public void escape(char[] ch, int start,int length, boolean isAttVal,
Writer writer) throws IOException {
writer.write(ch, start, length);
}
});
转自:http://techdive.in/java/jaxb-avoid-converting-lt-and-gt-during-marshalling
>更多相关文章
首页推荐
佛山市东联科技有限公司一直秉承“一切以用户价值为依归
- 01-11全球最受赞誉公司揭晓:苹果连续九年第一
- 12-09罗伯特·莫里斯:让黑客真正变黑
- 12-09谁闯入了中国网络?揭秘美国绝密黑客小组TA
- 12-09警示:iOS6 惊现“闪退”BUG
- 05-15奇安信:数据安全问题是医疗卫生行业数字化
- 05-15腾讯宣布混元文生图大模型开源
- 05-15网易云音乐与韩国知名娱乐公司Kakao达成战略
- 05-15阿联酋宣告正式开启“5G-A全国商用”计划,
- 05-15二十年未遇的强烈地磁暴来袭
相关文章
24小时热门资讯
24小时回复排行
热门推荐
最新资讯
操作系统
黑客防御