我想为我的地标添加一个描述,即一系列 html。当我运行编组器时,我得到一堆特殊字符串而不是特殊字符。即我的最终文件看起来像CDATA<html>
而不是CDATA<html>
.
我不想覆盖 JAK 编组器,所以我希望有一种简单的方法可以确保将我的确切字符串传递到文件中。
谢谢。
编组实际上转义了特殊字符"
to "
、&
to&
和<
to <
。
我的建议是使用字符串的替换功能,这实际上有助于将转义字符重新转换回正常字符。
try {
StringWriter sw = new StringWriter();
return marshaller.marshal(obj, sw);
} catch (JAXBException jaxbe) {
throw new XMLMarshalException(jaxbe);
}
使用 sw 对象,使用 sw.toString().replace() 将更改的字符替换回原来的字符。
这将确保您拥有与您想要的东西同步的东西。
希望这可以帮助..
创建一个实现 CharacterEscapeHandler 的 NoEscapeHandler(例如在 com.sun.xml.bind.marshaller.DumbEscapeHandler
import java.io.IOException;
import java.io.Writer;
import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
public class NoEscapeHandler implements CharacterEscapeHandler {
private NoEscapeHandler() {}
public static final CharacterEscapeHandler theInstance = new NoEscapeHandler();
public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
int limit = start+length;
for (int i = start; i < limit; i++) {
out.write(ch[i]);
}
}
}
然后设置编组器的属性
marshaller.setProperty("com.sun.xml.bind.characterEscapeHandler", NoEscapeHandler.theInstance);
或使用 DataWriter
StringWriter sw = new StringWriter();
DataWriter dw = new DataWriter(sw, "utf-8", NoEscapeHandler.theInstance);
使用 XmlStreamWriter 和 jaxb 片段时的解决方案
最终 XMLOutputFactory streamWriterFactory = XMLOutputFactory.newFactory(); streamWriterFactory.setProperty("escapeCharacters", false);