Java JAXB编组器更改<而不是>的编码

时间:2019-03-21 12:38:04

标签: java jaxb tags

拥有

for i, e in enumerate(mainlist):
  data = sublist_dict.get(e[0])
  if data: mainlist[i].append(data)

print(mainlist)
#=> [['RD-12', 12, 'a', 67], ['RD-13', 45, 'c'], ['RD-15', 50, 'e', 65]]

具有自由文本,例如“你好,我的内含粗体文本。”在节点

产生

String translationXsd = TranslationPropertyHelper.getFileLocation(PropertyKey.TRANSLATE_XSD_FILE);
  File translationXsdFile = new File(translationXsd);

  SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  Schema schema = schemaFactory.newSchema(translationXsdFile);

  JAXBContext jaxbContext = JAXBContext
      .newInstance(translationJob.getClass().getPackage().getName());
  Marshaller marshaller = jaxbContext.createMarshaller();
  OutputStream os = new FileOutputStream(pOutputFile);
  XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
  XMLStreamWriter xsw = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(os));
  marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
  marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
  marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, translationXsdFile.getName());
  marshaller.setSchema(schema);
  marshaller.marshal(translationJob, xsw);
  xsw.close();

期望是:

<freetextnode>hello i have &lt; b > bold &lt; / b > text inside.</freetextnode>

JavaEE 7。

1 个答案:

答案 0 :(得分:1)

您需要将封送与com.sun.xml.internal.bind.marshaller.DumbEscapeHandler合并。来自JavaDoc

  

转义高于US-ASCII代码范围的所有内容。后备位置。   适用于任何JDK,任何编码。

如何使用它的简单示例:

import com.sun.xml.internal.bind.marshaller.DataWriter;
import com.sun.xml.internal.bind.marshaller.DumbEscapeHandler;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import java.io.PrintWriter;

public class JaxbApp {

    public static void main(String[] args) throws Exception {
        FreeTextNode dataFile = new FreeTextNode();
        dataFile.setValue("hello i have < b > bold < / b > text inside.");
        JAXBContext jaxbContext = JAXBContext.newInstance(FreeTextNode.class);
        Marshaller marshaller = jaxbContext.createMarshaller();

        PrintWriter printWriter = new PrintWriter(System.out);
        DataWriter dataWriter = new DataWriter(printWriter, "UTF-8", DumbEscapeHandler.theInstance);
        marshaller.marshal(dataFile, dataWriter);
    }
}

@XmlRootElement(name = "freetextnode")
class FreeTextNode {

    private String value;

    @XmlValue
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

上面的代码显示:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<freetextnode>hello i have &lt; b &gt; bold &lt; / b &gt; text inside.</freetextnode>

另请参阅: