如何强制JAXB转义换行符

时间:2016-03-21 16:28:42

标签: java xml jaxb escaping newline

我试图使用JAXB编组程序来编组其中包含换行符的对象,并且我希望它能够以与<,>和运输相同的方式来逃避这些字符返回。我认为它只是一个开关,但格式化的输出似乎没有帮助

我使用的代码

import java.io.File;
import java.io.IOException;

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

public class testesr {
    public static void main(String[] args) throws IOException, JAXBException {
        Marshaller marshaller = JAXBContext.newInstance(TesterElement.class).createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        marshaller.marshal(new TesterElement(), new File("C:\\Temp\\temp.xml"));

        Runtime.getRuntime().exec("cmd /c START C:\\Temp\\temp.xml");
    }

    @XmlRootElement
    public static class TesterElement {
        String valueWithCarriageReturn = "some\rvalue";
        String valueWithNewLine = "some\nvalue";
        String valueWithBoth = "some\r\nvalue";
        String otherCharacters = "some < | > value";

        public String getOtherCharacters() {
            return otherCharacters;
        }

        public void setOtherCharacters(String otherCharacters) {
            this.otherCharacters = otherCharacters;
        }

        public String getValueWithCarriageReturn() {
            return valueWithCarriageReturn;
        }

        public void setValueWithCarriageReturn(String valueWithCarriageReturn) {
            this.valueWithCarriageReturn = valueWithCarriageReturn;
        }

        public String getValueWithNewLine() {
            return valueWithNewLine;
        }

        public void setValueWithNewLine(String valueWithNewLine) {
            this.valueWithNewLine = valueWithNewLine;
        }

        public String getValueWithBoth() {
            return valueWithBoth;
        }

        public void setValueWithBoth(String valueWithBoth) {
            this.valueWithBoth = valueWithBoth;
        }
    }
}

产生这个

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testerElement>
    <otherCharacters>some &lt; | &gt; value</otherCharacters>
    <valueWithBoth>some&#xD;
value</valueWithBoth>
    <valueWithCarriageReturn>some&#xD;value</valueWithCarriageReturn>
    <valueWithNewLine>some
value</valueWithNewLine>
</testerElement>

但是如何让它将新行字符打印到此?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testerElement>
    <otherCharacters>some &lt; | &gt; value</otherCharacters>
    <valueWithBoth>some&#xD;&#xA;value</valueWithBoth>
    <valueWithCarriageReturn>some&#xD;value</valueWithCarriageReturn>
    <valueWithNewLine>some&#xA;value</valueWithNewLine>
</testerElement>

0 个答案:

没有答案
相关问题