Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> JAXB - Avoid converting ( into < and ) into > during Marshalling

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

編輯:關於Android編程

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
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved