【问题标题】:How to keep string formatting when marshalling with JAK kml library使用 JAK kml 库编组时如何保持字符串格式
【发布时间】:2013-11-26 14:55:00
【问题描述】:

我想为我的地标添加一个描述,即一系列 html。当我运行编组器时,我得到一堆特殊字符串而不是特殊字符。即我的最终文件看起来像 CDATA<html> 而不是 CDATA<html>

我不想覆盖 JAK 编组器,所以我希望有一种简单的方法可以确保将我的确切字符串传递到文件中。

谢谢。

【问题讨论】:

    标签: java kml jak


    【解决方案1】:

    编组实际上是转义了特殊字符,""&&<<

    我的建议是使用字符串的替换功能,这实际上有助于将转义字符重新转换回正常字符。

        try {
                StringWriter sw = new StringWriter();
                return marshaller.marshal(obj, sw);
            } catch (JAXBException jaxbe) {
                throw new XMLMarshalException(jaxbe);
            }
    

    使用 sw 对象,使用 sw.toString().replace() 将更改的字符替换回原来的字符。

    这将确保您拥有与您想要的东西同步的东西。

    希望这会有所帮助..

    【讨论】:

    • 感谢 KmlFactory,createKml 你可以使用类似于 // return kml.marshal(System.out) StringWriter sw = new StringWriter() kml.marshal(sw) return sw.toString()
    【解决方案2】:
    1. 通用解决方案

    创建一个实现 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的属性

    marshaller.setProperty("com.sun.xml.bind.characterEscapeHandler", NoEscapeHandler.theInstance);
    

    或者使用 DataWriter

    StringWriter sw = new StringWriter();
    DataWriter dw = new DataWriter(sw, "utf-8", NoEscapeHandler.theInstance);
    
    1. 使用 XmlStreamWriter 和 jaxb framgments 时的解决方案

      最终的 XMLOutputFactory streamWriterFactory = XMLOutputFactory.newFactory(); streamWriterFactory.setProperty("escapeCharacters", false);

    From here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 2014-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多