JAXB - Avoid converting ( into < and ) into > during Marshalling

浏览:
字体:
发布时间:2013-12-20 16:18:48
来源:

In this article, let us see how to avoid converting < to &lt ; and > to &gt ; and & to &amp ; during JAXB Marshalling operation.

1. CharacterEscapeHandler creation
Create a custom Escape Handler by implementing the CharacterEscapeHandler interface as given below.

import com.sun.xml.bind.marshaller.CharacterEscapeHandler;

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 &lt; and > to &gt; 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
>更多相关文章
24小时热门资讯
24小时回复排行
资讯 | QQ | 安全 | 编程 | 数据库 | 系统 | 网络 | 考试 | 站长 | 关于东联 | 安全雇佣 | 搞笑视频大全 | 微信学院 | 视频课程 |
关于我们 | 联系我们 | 广告服务 | 免责申明 | 作品发布 | 网站地图 | 官方微博 | 技术培训
Copyright © 2007 - 2024 Vm888.Com. All Rights Reserved
粤公网安备 44060402001498号 粤ICP备19097316号 请遵循相关法律法规
');})();