使用 jackson-dataformat-xml 转义引号

gor*_*rrr 4 java xml escaping jackson jackson-dataformat-xml

我需要帮助jackson-dataformat-xml。我需要将List<String>using序列化XmlMapper到 xml 中,并对引号"\xe2\x86\x92进行编码&quot;

\n\n

但是在序列化XmlMapper对所有其他特殊符号(<、等)进行编码后,但完全忽略引号(和)...如果我在序列化之前手动>编码字符串,内容会变得混乱,因为里面有并且它的序列化不是当然。&\'"&quot;\'&\'&amp;quot;

\n\n

也许有人知道如何让它发挥作用?\n另外,有没有一种解决方法可以List<String>使用@JacksonRawValue或类似的方法在字段上禁用自动特殊符号编码?此注释在简单(非数组)字段上效果很好,但在List<String>.

\n\n

谢谢。

\n

gor*_*rrr 6

问题是这样解决的。我使用了 woodbox Stax2 扩展。这很有帮助。 https://github.com/FasterXML/jackson-dataformat-xml/issues/75

XmlMapper xmlMapper = new XmlMapper(module);
xmlMapper.getFactory().getXMLOutputFactory().setProperty(XMLOutputFactory2.P_TEXT_ESCAPER, 
new CustomXmlEscapingWriterFactory());
Run Code Online (Sandbox Code Playgroud)

这是工厂。

public class CustomXmlEscapingWriterFactory implements EscapingWriterFactory {
public Writer createEscapingWriterFor(final Writer out, String enc) {
    return new Writer(){
        @Override
        public void write(char[] cbuf, int off, int len) throws IOException {
            String val = "";
            for (int i = off; i < len; i++) {
                val += cbuf[i];
            }
            String escapedStr =  StringEscapeUtils.escapeXml(val);
            out.write(escapedStr);
        }

        @Override
        public void flush() throws IOException {
            out.flush();
        }

        @Override
        public void close() throws IOException {
            out.close();
        }
      };
    }

    public Writer createEscapingWriterFor(OutputStream out, String enc) {
        throw new IllegalArgumentException("not supported");
    }
}
Run Code Online (Sandbox Code Playgroud)