小编典典

例如,在编组为XML时,是否可以强制JAXB不要将“转换为”?

java

我有一个使用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>

如您所见,该回调从未显示。(一旦调用了回调,我将担心让它实际执行我想要的操作。)

-


阅读 213

收藏
2020-09-15

共1个答案

小编典典

我的队友找到的解决方案:

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。

2020-09-15