[英]JAXB How to append and XML String into a XML element?
我正在尝试添加XML元素,另一个是字符串的XML。 问题出在我生成XML文件编码不正确时,这使我产生了<> HTML的值。
JAXBContext jaxbContext = JAXBContext.newInstance(ExpedienteType.class);
String XMLDatosEspecificos = "<![CDATA[" + XMLDatosEspecificos + "]]>";
expedienteType.setDATOSESPECIFICOS(XMLDatosEspecificos);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
marshaller.setProperty(Marshaller.JAXB_ENCODING,"UTF-8");
JAXBElement<ExpedienteType> jaxbElement = new JAXBElement<ExpedienteType>(
new QName("", "Expediente"), ExpedienteType.class, expedienteType);
ByteArrayOutputStream os = new ByteArrayOutputStream();
marshaller.marshal(jaxbElement, os);
File f = new File("file.xml");
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(os.toByteArray());
os.close();
fos.close();
XML的结果在这里。
<DATOS_ESPECIFICOS><![CDATA[<nombre>pepito</nombre><apellidos>grillo</apellidos>]]>;</DATOS_ESPECIFICOS>
我得到的结果是.....
<DATOS_ESPECIFICOS><![CDATA[<nombre>pepito</nombre><apellidos>grillo</apellidos>]]></DATOS_ESPECIFICOS>
详细说明我的意见-默认情况下,JAXB会转义您在element上设置的所有文本。
您可以使用如何防止JAXB转义字符串中描述的解决方案之一来禁用转义。
但是,我看到您真正需要的只是将文本放在CDATA部分中。 这可以使用此处描述的解决方案之一来实现: 如何使用JAXB生成CDATA块?
最好的解决方案是我实施的解决方案。 还需要创建一个处理程序,该处理程序无需更改就可以写所有发生的事情,从而可以在不更改任何字符的情况下编写文本。
import java.io.IOException;
import java.io.Writer;
import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
public class MyEscapeHandler implements CharacterEscapeHandler {
@Override
public void escape(char[] ch, int start, int length, boolean isAttVal,
Writer out) throws IOException {
out.write(ch, start, length);
}
}
在实现XML创建的类中,将其添加。
JAXBContext jaxbContext = JAXBContext
.newInstance(ExpedienteType.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
true);
marshaller.setProperty(Marshaller.JAXB_ENCODING,
"ISO-8859-1");
StringBuffer strBuff = new StringBuffer("");
strBuff.append("PLAT2_");
strBuff.append(expedienteType.getNEXPEDIENTE().replace("/", "_"));
CharacterEscapeHandler escapeHandler = new MyEscapeHandler();
marshaller.setProperty("com.sun.xml.bind.characterEscapeHandler", escapeHandler);
JAXBElement<ExpedienteType> jaxbElement = new JAXBElement<ExpedienteType>(
new QName("", "Expediente"), ExpedienteType.class,
expedienteType);
ByteArrayOutputStream os = new ByteArrayOutputStream();
marshaller.marshal(jaxbElement, os);
最终的XML完美创建。
<DATOS_ESPECIFICOS><![CDATA[<nombre>pepito</nombre><apellidos>grillo</apellidos>]]></DATOS_ESPECIFICOS>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.