我可以强制 JAXB 不转换“”吗?例如,当编组到 XML 时,将其转换为 "

发布于 2024-08-06 05:05:14 字数 1954 浏览 6 评论 0原文

我有一个使用 JAXB 编组为 XML 的对象。一个元素包含一个包含引号 (") 的字符串。生成的 XML 在 " 所在的位置包含 "

尽管这通常是首选,但我需要我的输出与旧系统相匹配。如何强制 JAXB 不转换 HTML 实体?

——

谢谢各位的回复。但是,我从未看到处理程序 escape() 被调用。你能看一下我做错了什么吗?谢谢!

package org.dc.model;

import java.io.IOException;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.dc.generated.Shiporder;

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

public class PleaseWork {
    public void prettyPlease() throws JAXBException {
        Shiporder shipOrder = new Shiporder();
        shipOrder.setOrderid("Order's ID");
        shipOrder.setOrderperson("The woman said, \"How ya doin & stuff?\"");

        JAXBContext context = JAXBContext.newInstance("org.dc.generated");
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(CharacterEscapeHandler.class.getName(),
                new CharacterEscapeHandler() {
                    @Override
                    public void escape(char[] ch, int start, int length,
                            boolean isAttVal, Writer out) throws IOException {
                        out.write("Called escape for characters = " + ch.toString());
                    }
                });
        marshaller.marshal(shipOrder, System.out);
    }

    public static void main(String[] args) throws Exception {
        new PleaseWork().prettyPlease();
    }
}

--

输出是这样的:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<shiporder orderid="Order's ID">
    <orderperson>The woman said, &quot;How ya doin &amp; stuff?&quot;</orderperson>
</shiporder>

正如您所看到的,回调永远不会显示。 (一旦我得到回调被调用,我就会担心它是否真的做我想做的事。)

--

I have an Object that is being marshalled to XML using JAXB. One element contains a String that includes quotes ("). The resulting XML has " where the " existed.

Even though this is normally preferred, I need my output to match a legacy system. How do I force JAXB to NOT convert the HTML entities?

--

Thank you for the replies. However, I never see the handler escape() called. Can you take a look and see what I'm doing wrong? Thanks!

package org.dc.model;

import java.io.IOException;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.dc.generated.Shiporder;

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

public class PleaseWork {
    public void prettyPlease() throws JAXBException {
        Shiporder shipOrder = new Shiporder();
        shipOrder.setOrderid("Order's ID");
        shipOrder.setOrderperson("The woman said, \"How ya doin & stuff?\"");

        JAXBContext context = JAXBContext.newInstance("org.dc.generated");
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(CharacterEscapeHandler.class.getName(),
                new CharacterEscapeHandler() {
                    @Override
                    public void escape(char[] ch, int start, int length,
                            boolean isAttVal, Writer out) throws IOException {
                        out.write("Called escape for characters = " + ch.toString());
                    }
                });
        marshaller.marshal(shipOrder, System.out);
    }

    public static void main(String[] args) throws Exception {
        new PleaseWork().prettyPlease();
    }
}

--

The output is this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<shiporder orderid="Order's ID">
    <orderperson>The woman said, "How ya doin & stuff?"</orderperson>
</shiporder>

and as you can see, the callback is never displayed. (Once I get the callback being called, I'll worry about having it actually do what I want.)

--

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

人疚 2024-08-13 05:05:15

@Elliot 您可以使用它来使编组器能够输入characterEscape函数。
这很奇怪,但如果您设置“Unicode”而不是“UTF-8”,它就会起作用。
在设置CharacterEscapeHandler属性之前或之后添加它。

marshaller.setProperty(Marshaller.JAXB_ENCODING, "Unicode");

但是,不要仅通过检查 IDE 中的控制台来确定,因为它的显示应取决于工作区编码。最好也从这样的文件中检查它:

marshaller.marshal(shipOrder, new File("C:\\shipOrder.txt"));

@Elliot you can use this in order to enable marshaller to enter characterEscape function.
It is wierd but it works if you set "Unicode" instead of "UTF-8".
Add this just before or after you set CharacterEscapeHandler property.

marshaller.setProperty(Marshaller.JAXB_ENCODING, "Unicode");

However don't be sure just only by checking your console within your IDE, because it should be shown depend on the workspace encoding. It is better to check it also from a file like that:

marshaller.marshal(shipOrder, new File("C:\\shipOrder.txt"));
又爬满兰若 2024-08-13 05:05:15

我发现同样的问题
我使用 xmlWriter 修复了这个问题
在 xmlWriter 文件中有一种方法 isEscapeText() 和 setEscapeTest
默认情况下是 true
如果您不想在 < 之间进行转换到<这个时候你需要setEscapeTest(false);在编组过程中,

JAXBContext jaxbContext = JAXBContext.newInstance(your class);
Marshaller marshaller = jaxbContext.createMarshaller();

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

// Create a filter that will remove the xmlns attribute
NamespaceFilter outFilter = new NamespaceFilter(null, false);

// Do some formatting, this is obviously optional and may effect
// performance
OutputFormat format = new OutputFormat();
format.setIndent(true);
format.setNewlines(true);

// Create a new org.dom4j.io.XMLWriter that will serve as the
// ContentHandler for our filter.
XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
writer.setEscapeText(false); // <----------------- this line
// Attach the writer to the filter
outFilter.setContentHandler(writer);
// marshalling
marshaller.marshal(piaDto, outFilter);
marshaller.marshal(piaDto, System.out);

此更改writer.setEscapeText(false);解决了我的问题
希望这个改变对你有帮助

i found same issue
i fixed this using xmlWriter
in xmlWriter file there is one method isEscapeText() and setEscapeTest
that is by default true
if you dont want transformation between < to < that time you need to setEscapeTest(false); during marshalling

JAXBContext jaxbContext = JAXBContext.newInstance(your class);
Marshaller marshaller = jaxbContext.createMarshaller();

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

// Create a filter that will remove the xmlns attribute
NamespaceFilter outFilter = new NamespaceFilter(null, false);

// Do some formatting, this is obviously optional and may effect
// performance
OutputFormat format = new OutputFormat();
format.setIndent(true);
format.setNewlines(true);

// Create a new org.dom4j.io.XMLWriter that will serve as the
// ContentHandler for our filter.
XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
writer.setEscapeText(false); // <----------------- this line
// Attach the writer to the filter
outFilter.setContentHandler(writer);
// marshalling
marshaller.marshal(piaDto, outFilter);
marshaller.marshal(piaDto, System.out);

this change writer.setEscapeText(false); fixed my issue
hope this changes helpful to you

半枫 2024-08-13 05:05:15

似乎可以使用 Sun 的JAXB实现,虽然我自己没有做过。

Seems like it is possible with Sun's JAXB implementation, although I've not done it myself.

巡山小妖精 2024-08-13 05:05:15

我检查了 XML 规范。 http://www.w3.org/TR/REC-xml/# sec-references 说“格式良好的文档不需要声明以下任何实体:amp、lt、gt、apos、quot。”因此,遗留系统使用的 XML 解析器似乎不符合要求。

(我知道它不能解决您的问题,但至少能够说出哪个组件损坏了是件好事)。

I checked the XML specification. http://www.w3.org/TR/REC-xml/#sec-references says "well-formed documents need not declare any of the following entities: amp, lt, gt, apos, quot. " so it appears that the XML parser used by the legacy system is not conformant.

(I know that it does not solve your problem, but it is at least nice to be able to say which component is broken).

多情出卖 2024-08-13 05:05:15

阅读其他帖子后,这对我有用:

javax.xml.bind.JAXBContext jc = javax.xml.bind.JAXBContext.newInstance(object);
marshaller = jc.createMarshaller();         marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8");                   marshaller.setProperty(CharacterEscapeHandler.class.getName(), new CustomCharacterEscapeHandler());


public static class CustomCharacterEscapeHandler implements CharacterEscapeHandler {
        /**
         * Escape characters inside the buffer and send the output to the Writer.
         * (prevent <b> to be converted <b> but still ok for a<5.)
         */
        public void escape(char[] buf, int start, int len, boolean isAttValue, Writer out) throws IOException {
            if (buf != null){
                StringBuilder sb = new StringBuilder();
                for (int i = start; i < start + len; i++) {
                    char ch = buf[i];

                    //by adding these, it prevent the problem happened when unmarshalling
                    if (ch == '&') {
                        sb.append("&");
                        continue;
                    }

                    if (ch == '"' && isAttValue) {
                        sb.append(""");
                        continue;
                    }

                    if (ch == '\'' && isAttValue) {
                        sb.append("'");
                        continue;
                    }


                    // otherwise print normally
                    sb.append(ch);
                }

                //Make corrections of unintended changes
                String st = sb.toString();

                st = st.replace("&quot;", """)
                       .replace("&lt;", "<")
                       .replace("&gt;", ">")
                       .replace("&apos;", "'")
                       .replace("&amp;", "&");

                out.write(st);
            }
        }
    }

This works for me after reading other posts:

javax.xml.bind.JAXBContext jc = javax.xml.bind.JAXBContext.newInstance(object);
marshaller = jc.createMarshaller();         marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8");                   marshaller.setProperty(CharacterEscapeHandler.class.getName(), new CustomCharacterEscapeHandler());


public static class CustomCharacterEscapeHandler implements CharacterEscapeHandler {
        /**
         * Escape characters inside the buffer and send the output to the Writer.
         * (prevent <b> to be converted <b> but still ok for a<5.)
         */
        public void escape(char[] buf, int start, int len, boolean isAttValue, Writer out) throws IOException {
            if (buf != null){
                StringBuilder sb = new StringBuilder();
                for (int i = start; i < start + len; i++) {
                    char ch = buf[i];

                    //by adding these, it prevent the problem happened when unmarshalling
                    if (ch == '&') {
                        sb.append("&");
                        continue;
                    }

                    if (ch == '"' && isAttValue) {
                        sb.append(""");
                        continue;
                    }

                    if (ch == '\'' && isAttValue) {
                        sb.append("'");
                        continue;
                    }


                    // otherwise print normally
                    sb.append(ch);
                }

                //Make corrections of unintended changes
                String st = sb.toString();

                st = st.replace("&quot;", """)
                       .replace("&lt;", "<")
                       .replace("&gt;", ">")
                       .replace("&apos;", "'")
                       .replace("&amp;", "&");

                out.write(st);
            }
        }
    }
一萌ing 2024-08-13 05:05:15

有趣,但对于字符串,你至少可以尝试一下,

Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter sw = new StringWriter();
marshaller.marshal(data, sw);
sw.toString();

至少对我来说,这不会转义引号

interesting but with strings you can try out

Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter sw = new StringWriter();
marshaller.marshal(data, sw);
sw.toString();

at least for me this do not escape quotes

倾其所爱 2024-08-13 05:05:15

当使用sun的Marshaller实现时,最简单的方法是提供您自己的CharacterEscapeEncoder的实现,它不会转义任何内容。

    Marshaller m = jcb.createMarshaller();
m.setProperty(
    "com.sun.xml.bind.marshaller.CharacterEscapeHandler",
    new NullCharacterEscapeHandler());

public class NullCharacterEscapeHandler implements CharacterEscapeHandler {

    public NullCharacterEscapeHandler() {
        super();
    }


    public void escape(char[] ch, int start, int length, boolean isAttVal, Writer writer) throws IOException {
        writer.write( ch, start, length );
    }
}

The simplest way, when using sun's Marshaller implementation is to provide your own implementation of the CharacterEscapeEncoder which does not escape anything.

    Marshaller m = jcb.createMarshaller();
m.setProperty(
    "com.sun.xml.bind.marshaller.CharacterEscapeHandler",
    new NullCharacterEscapeHandler());

With

public class NullCharacterEscapeHandler implements CharacterEscapeHandler {

    public NullCharacterEscapeHandler() {
        super();
    }


    public void escape(char[] ch, int start, int length, boolean isAttVal, Writer writer) throws IOException {
        writer.write( ch, start, length );
    }
}
海夕 2024-08-13 05:05:15

由于某种原因,我没有时间去了解,它在设置时对我有用,

marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");

而不是使用 "UTF-8""Unicode"

我建议你尝试一下,正如 @Javatar 所说,检查它们是否转储到文件,使用:

marshaller.marshal(shipOrder, new File("<test_file_path>"));

并使用像 notepad++

For some reason I have no time to find out, it worked for me when setting

marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");

As opposed to using "UTF-8" or "Unicode"

I suggest you try them, and as @Javatar said, check them dumping to file using:

marshaller.marshal(shipOrder, new File("<test_file_path>"));

and opening it with a a decent text editor like notepad++

毁梦 2024-08-13 05:05:15

由于上述原因(它是一个内部类),我建议不要使用 CharacterEscapeHandler。相反,您可以使用 Woodstox 并将您自己的 EscapingWriterFactory 提供给 XMLStreamWriter。类似于:

XMLOutputFactory2 xmlOutputFactory = (XMLOutputFactory2)XMLOutputFactory.newFactory();
xmlOutputFactory.setProperty(XMLOutputFactory2.P_TEXT_ESCAPER, new EscapingWriterFactory() {

    @Override
    public Writer createEscapingWriterFor(Writer w, String enc) {
        return new EscapingWriter(w);
    }

    @Override
    public Writer createEscapingWriterFor(OutputStream out, String enc) throws UnsupportedEncodingException {
        return new EscapingWriter(new OutputStreamWriter(out, enc));
    }

});

marshaller.marshal(model, xmlOutputFactory.createXMLStreamWriter(out);

如何编写 EscapingWriter 的示例可以在 CharacterEscapingTest

I would advise against using CharacterEscapeHandler for the reasons mentioned above (it's an internal class). Instead you can use Woodstox and supply your own EscapingWriterFactory to a XMLStreamWriter. Something like:

XMLOutputFactory2 xmlOutputFactory = (XMLOutputFactory2)XMLOutputFactory.newFactory();
xmlOutputFactory.setProperty(XMLOutputFactory2.P_TEXT_ESCAPER, new EscapingWriterFactory() {

    @Override
    public Writer createEscapingWriterFor(Writer w, String enc) {
        return new EscapingWriter(w);
    }

    @Override
    public Writer createEscapingWriterFor(OutputStream out, String enc) throws UnsupportedEncodingException {
        return new EscapingWriter(new OutputStreamWriter(out, enc));
    }

});

marshaller.marshal(model, xmlOutputFactory.createXMLStreamWriter(out);

An example of how to write an EscapingWriter can be seen in CharacterEscapingTest.

故事↓在人 2024-08-13 05:05:15

尝试了以上所有解决方案后,终于得出结论。

通过自定义转义处理程序的编组逻辑。

final StringWriter sw = new StringWriter();
    final Class classType = fixml.getClass();
    final JAXBContext jaxbContext = JAXBContext.newInstance(classType);
    final Marshaller marshaller = jaxbContext.createMarshaller();
    final JAXBElement<T> fixmsg = new JAXBElement<T>(new QName(namespaceURI, localPart), classType, fixml);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(CharacterEscapeHandler.class.getName(), new JaxbCharacterEscapeHandler());
    marshaller.marshal(fixmsg, sw);
    return sw.toString();

自定义转义处理程序如下:

import java.io.IOException;
import java.io.Writer;

public class JaxbCharacterEscapeHandler implements CharacterEscapeHandler {

    public void escape(char[] buf, int start, int len, boolean isAttValue,
                    Writer out) throws IOException {

            for (int i = start; i < start + len; i++) {
                    char ch = buf[i];
                    out.write(ch);
            }
    }
}

After trying all the above solutions, finally came to the conclusion.

your marshaling logic through the custom escape handler.

final StringWriter sw = new StringWriter();
    final Class classType = fixml.getClass();
    final JAXBContext jaxbContext = JAXBContext.newInstance(classType);
    final Marshaller marshaller = jaxbContext.createMarshaller();
    final JAXBElement<T> fixmsg = new JAXBElement<T>(new QName(namespaceURI, localPart), classType, fixml);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(CharacterEscapeHandler.class.getName(), new JaxbCharacterEscapeHandler());
    marshaller.marshal(fixmsg, sw);
    return sw.toString();

And the custom escape handler is as follow:

import java.io.IOException;
import java.io.Writer;

public class JaxbCharacterEscapeHandler implements CharacterEscapeHandler {

    public void escape(char[] buf, int start, int len, boolean isAttValue,
                    Writer out) throws IOException {

            for (int i = start; i < start + len; i++) {
                    char ch = buf[i];
                    out.write(ch);
            }
    }
}
笑脸一如从前 2024-08-13 05:05:14

我的队友发现的解决方案:

PrintWriter printWriter = new PrintWriter(new FileWriter(xmlFile));
DataWriter dataWriter = new DataWriter(printWriter, "UTF-8", DumbEscapeHandler.theInstance);
marshaller.marshal(request, dataWriter);

不要将 xmlFile 传递给 marshal(),而是传递知道编码和适当的转义处理程序(如果有)的 DataWriter。

注意:由于 DataWriter 和 DumbEscapeHandler 都在 com.sun.xml.internal.bind.marshaller 包中,因此您必须引导 javac。

Solution my teammate found:

PrintWriter printWriter = new PrintWriter(new FileWriter(xmlFile));
DataWriter dataWriter = new DataWriter(printWriter, "UTF-8", DumbEscapeHandler.theInstance);
marshaller.marshal(request, dataWriter);

Instead of passing the xmlFile to marshal(), pass the DataWriter which knows both the encoding and an appropriate escape handler, if any.

Note: Since DataWriter and DumbEscapeHandler are both within the com.sun.xml.internal.bind.marshaller package, you must bootstrap javac.

世界如花海般美丽 2024-08-13 05:05:14

我刚刚将自定义处理程序制作为这样的类:

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

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

public class XmlCharacterHandler implements CharacterEscapeHandler {

    public void escape(char[] buf, int start, int len, boolean isAttValue,
            Writer out) throws IOException {
        StringWriter buffer = new StringWriter();

        for (int i = start; i < start + len; i++) {
            buffer.write(buf[i]);
        }

        String st = buffer.toString();

        if (!st.contains("CDATA")) {
            st = buffer.toString().replace("&", "&").replace("<", "<")
                .replace(">", ">").replace("'", "'")
                .replace("\"", """);

        }
        out.write(st);
        System.out.println(st);
    }

}

在编组器方法中只需调用:

marshaller.setProperty(CharacterEscapeHandler.class.getName(),
                new XmlCharacterHandler());

它工作正常。

I have just made my custom handler as a class like this:

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

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

public class XmlCharacterHandler implements CharacterEscapeHandler {

    public void escape(char[] buf, int start, int len, boolean isAttValue,
            Writer out) throws IOException {
        StringWriter buffer = new StringWriter();

        for (int i = start; i < start + len; i++) {
            buffer.write(buf[i]);
        }

        String st = buffer.toString();

        if (!st.contains("CDATA")) {
            st = buffer.toString().replace("&", "&").replace("<", "<")
                .replace(">", ">").replace("'", "'")
                .replace("\"", """);

        }
        out.write(st);
        System.out.println(st);
    }

}

in the marshaller method simply call:

marshaller.setProperty(CharacterEscapeHandler.class.getName(),
                new XmlCharacterHandler());

it works fine.

九歌凝 2024-08-13 05:05:14

我已经玩了一下你的示例并调试了 JAXB 代码。这似乎与所使用的 UTF-8 编码有关。 MarshallerImpl 的 escapeHandler 属性似乎设置正确。然而,它并不是在所有情况下都被使用。如果我搜索 MarshallerImpl.createEscapeHandler() 的调用,我发现:

public XmlOutput createWriter( OutputStream os, String encoding ) throws JAXBException {
    // UTF8XmlOutput does buffering on its own, and
    // otherwise createWriter(Writer) inserts a buffering,
    // so no point in doing a buffering here.

    if(encoding.equals("UTF-8")) {
        Encoded[] table = context.getUTF8NameTable();
        final UTF8XmlOutput out;
        if(isFormattedOutput())
            out = new IndentingUTF8XmlOutput(os,indent,table);
        else {
            if(c14nSupport)
                out = new C14nXmlOutput(os,table,context.c14nSupport);
            else
                out = new UTF8XmlOutput(os,table);
        }
        if(header!=null)
            out.setHeader(header);
        return out;
    }

    try {
        return createWriter(
            new OutputStreamWriter(os,getJavaEncoding(encoding)),
            encoding );
    } catch( UnsupportedEncodingException e ) {
        throw new MarshalException(
            Messages.UNSUPPORTED_ENCODING.format(encoding),
            e );
    }
}

请注意,在您的设置中,顶部部分 (...equals("UTF-8")...)被考虑在内。然而,这个不采用escapeHandler。但是,如果将编码设置为任何其他编码,则会调用此方法的底部部分 (createWriter(OutputStream, String)),并且此方法使用 escapeHandler,因此 EH 会播放其角色。
因此,添加...

    marshaller.setProperty(Marshaller.JAXB_ENCODING, "ASCII");

会使您的自定义 CharacterEscapeHandler 被调用。
不太确定,但我猜这是 JAXB 中的一种错误。

I've been playing with your example a bit and debugging the JAXB code. And it seems it's something specific about UTF-8 encoding used. The escapeHandler property of MarshallerImpl seems to be set properly. However it's being used not in every context. If I searched for calls of MarshallerImpl.createEscapeHandler() I found:

public XmlOutput createWriter( OutputStream os, String encoding ) throws JAXBException {
    // UTF8XmlOutput does buffering on its own, and
    // otherwise createWriter(Writer) inserts a buffering,
    // so no point in doing a buffering here.

    if(encoding.equals("UTF-8")) {
        Encoded[] table = context.getUTF8NameTable();
        final UTF8XmlOutput out;
        if(isFormattedOutput())
            out = new IndentingUTF8XmlOutput(os,indent,table);
        else {
            if(c14nSupport)
                out = new C14nXmlOutput(os,table,context.c14nSupport);
            else
                out = new UTF8XmlOutput(os,table);
        }
        if(header!=null)
            out.setHeader(header);
        return out;
    }

    try {
        return createWriter(
            new OutputStreamWriter(os,getJavaEncoding(encoding)),
            encoding );
    } catch( UnsupportedEncodingException e ) {
        throw new MarshalException(
            Messages.UNSUPPORTED_ENCODING.format(encoding),
            e );
    }
}

Note that in your setup the top section (...equals("UTF-8")...) is taken into consideration. However this one doesn't take the escapeHandler. However if you set the encoding to any other, the bottom part of this method is called (createWriter(OutputStream, String)) and this one uses escapeHandler, so EH plays its role.
So, adding...

    marshaller.setProperty(Marshaller.JAXB_ENCODING, "ASCII");

makes your custom CharacterEscapeHandler be called.
Not really sure, but I would guess this is kind of bug in JAXB.

却一份温柔 2024-08-13 05:05:14

我想说最简单的方法是重写 CharacterEscapeHandler

marshaller.setProperty("com.sun.xml.bind.characterEscapeHandler", new CharacterEscapeHandler() {
    @Override
    public void escape(char[] ch, int start, int length, boolean isAttVal,
                       Writer out) throws IOException {
        out.write(ch, start, length);
    }
});

I would say that easiest way to do is by overriding CharacterEscapeHandler :

marshaller.setProperty("com.sun.xml.bind.characterEscapeHandler", new CharacterEscapeHandler() {
    @Override
    public void escape(char[] ch, int start, int length, boolean isAttVal,
                       Writer out) throws IOException {
        out.write(ch, start, length);
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文