下面列出了javax.xml.bind.Marshaller#setProperty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Obtains the tag name of the root element.
*/
private void sniff() {
RootElementSniffer sniffer = new RootElementSniffer(false);
try {
if (rawContext != null) {
Marshaller m = rawContext.createMarshaller();
m.setProperty("jaxb.fragment", Boolean.TRUE);
m.marshal(jaxbObject,sniffer);
} else
bridge.marshal(jaxbObject,sniffer,null);
} catch (JAXBException e) {
// if it's due to us aborting the processing after the first element,
// we can safely ignore this exception.
//
// if it's due to error in the object, the same error will be reported
// when the readHeader() method is used, so we don't have to report
// an error right now.
nsUri = sniffer.getNsUri();
localName = sniffer.getLocalName();
}
}
private void toClipboard(ObjectModel model) {
Clipboard clipboard = Clipboard.getSystemClipboard();
Map<DataFormat, Object> content = new HashMap();
try {
Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter writer = new StringWriter();
// output pretty printed
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.marshal(model, writer);
content.put(DATA_FORMAT_JAXB, writer.toString());
content.put(DataFormat.PLAIN_TEXT, writer.toString());
clipboard.setContent(content);
}
catch (Exception ex) {
LOG.log(Level.WARNING, "Unable to put content to clipboard", ex);
}
}
/**
* 创建Marshaller并设定encoding(可为null).
* 线程不安全,需要每次创建或pooling。
*/
public Marshaller createMarshaller(String encoding) {
try {
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
if (StringUtils.isNotBlank(encoding)) {
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
}
return marshaller;
} catch (JAXBException e) {
LangUtils.throwBaseException(e);
}
return null;
}
/**
* @throws Exception
*/
public void testPersistenceVersion2() throws Exception {
final JAXBContext ctx = JAXBContextFactory.newInstance(Persistence.class);
final Unmarshaller unmarshaller = ctx.createUnmarshaller();
final URL resource = this.getClass().getClassLoader().getResource("persistence_2.0-example.xml");
final InputStream in = resource.openStream();
final java.lang.String expected = readContent(in);
final Persistence element = (Persistence) unmarshaller.unmarshal(new ByteArrayInputStream(expected.getBytes()));
unmarshaller.setEventHandler(new TestValidationEventHandler());
System.out.println("unmarshalled");
final Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty("jaxb.formatted.output", true);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
marshaller.marshal(element, baos);
final String actual = new String(baos.toByteArray());
final Diff myDiff = new Diff(expected, actual);
myDiff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
assertTrue("Files are similar " + myDiff, myDiff.similar());
}
@Override
public void writeTo(TopologiesResource.HrefListing instance,
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException {
try {
Map<String, Object> properties = new HashMap<>(1);
properties.put( JAXBContextProperties.MEDIA_TYPE, mediaType.toString());
JAXBContext context = JAXBContext.newInstance(new Class[]{TopologiesResource.HrefListing.class}, properties);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(instance, entityStream);
} catch (JAXBException e) {
throw new IOException(e);
}
}
public static void writeXml()
{
if (newAdded > 0)
{
try
{
JAXBContext jaxbContext = JAXBContext.newInstance( Players.class );
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
new File("./data/appearances/").mkdirs();
jaxbMarshaller.marshal( players, new File( fileName ) );
}
catch (JAXBException e)
{
PacketSamurai.getUserInterface().log("Xml:"+ e.getMessage());
}
PacketSamurai.getUserInterface().log("Export [PlayerAppearance] - Written successfully "+newAdded+" new PlayerAppearances - You have now a total of ["+playerByName.size()+"] PlayerAppearances!");
newAdded = 0;
}
else PacketSamurai.getUserInterface().log("Export [PlayerAppearance] - Nothing to Export..");
}
public static String mcgGlobalToXml(McgGlobal mcgGlobal) {
String result = null;
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
JAXBContext context = JAXBContext.newInstance(McgGlobal.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// m.setProperty(Marshaller.JAXB_ENCODING, "GBK"); //防止文件中文乱码
m.marshal(mcgGlobal, os);
result = new String(os.toByteArray(), Constants.CHARSET);
os.close();
} catch (Exception e) {
logger.error("mcgGlobal转换xml出错,mcgGlobal对象数据:{},异常信息:{}", JSON.toJSONString(mcgGlobal), e.getMessage());
}
return result;
}
/**
* Obtains the tag name of the root element.
*/
private void sniff() {
RootElementSniffer sniffer = new RootElementSniffer(false);
try {
if (rawContext != null) {
Marshaller m = rawContext.createMarshaller();
m.setProperty("jaxb.fragment", Boolean.TRUE);
m.marshal(jaxbObject,sniffer);
} else
bridge.marshal(jaxbObject,sniffer,null);
} catch (JAXBException e) {
// if it's due to us aborting the processing after the first element,
// we can safely ignore this exception.
//
// if it's due to error in the object, the same error will be reported
// when the readHeader() method is used, so we don't have to report
// an error right now.
nsUri = sniffer.getNsUri();
localName = sniffer.getLocalName();
}
}
@Override
public void writePayloadTo(XMLStreamWriter sw) throws XMLStreamException {
try {
// MtomCodec sets its own AttachmentMarshaller
AttachmentMarshaller am = (sw instanceof MtomStreamWriter)
? ((MtomStreamWriter)sw).getAttachmentMarshaller()
: new AttachmentMarshallerImpl(attachmentSet);
// Get the encoding of the writer
String encoding = XMLStreamWriterUtil.getEncoding(sw);
// Get output stream and use JAXB UTF-8 writer
OutputStream os = bridge.supportOutputStream() ? XMLStreamWriterUtil.getOutputStream(sw) : null;
if (rawContext != null) {
Marshaller m = rawContext.createMarshaller();
m.setProperty("jaxb.fragment", Boolean.TRUE);
m.setAttachmentMarshaller(am);
if (os != null) {
m.marshal(jaxbObject, os);
} else {
m.marshal(jaxbObject, sw);
}
} else {
if (os != null && encoding != null && encoding.equalsIgnoreCase(SOAPBindingCodec.UTF8_ENCODING)) {
bridge.marshal(jaxbObject, os, sw.getNamespaceContext(), am);
} else {
bridge.marshal(jaxbObject, sw, am);
}
}
//cleanup() is not needed since JAXB doesn't keep ref to AttachmentMarshaller
//am.cleanup();
} catch (JAXBException e) {
// bug 6449684, spec 4.3.4
throw new WebServiceException(e);
}
}
public static void generateCbecMessageCiq(Object object, String dir, String backDir) {
if (null == object) {
return;
}
JAXBContext context = null;
Marshaller marshaller = null;
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
SimpleDateFormat sdfToday = new SimpleDateFormat("yyyyMMdd");
String fileName = "FILE_PAYMENT_" + sdf.format(calendar.getTime());
File cbecMessage = new File(dir + fileName + ".xml");
File backCbecMessage = new File(backDir + sdfToday.format(calendar.getTime()) + "/" + fileName + ".xml");
File backDirFile = new File(backDir + sdfToday.format(calendar.getTime()));
try {
context = JAXBContext.newInstance(object.getClass());
marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
// marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
if (!backDirFile.exists()) {
backDirFile.mkdir();
}
marshaller.marshal(object, backCbecMessage);
marshaller.marshal(object, cbecMessage);
} catch (Exception e) {
e.printStackTrace();
logger.equals(e);
}
}
public void marshal(Marshaller m, Object object, OutputStream output, NamespaceContext nsContext) throws JAXBException {
m.setProperty(Marshaller.JAXB_FRAGMENT,true);
try {
((MarshallerImpl)m).marshal(object,output,nsContext);
} finally {
m.setProperty(Marshaller.JAXB_FRAGMENT,false);
}
}
public void marshal(Marshaller m, Object object, XMLStreamWriter output) throws JAXBException {
m.setProperty(Marshaller.JAXB_FRAGMENT,true);
try {
m.marshal(object,output);
} finally {
m.setProperty(Marshaller.JAXB_FRAGMENT,false);
}
}
protected String getMarshalledObject(Object object) throws Throwable {
JAXBContext context = JAXBContext.newInstance(object.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(object, writer);
return writer.toString();
}
private Marshaller getUDDIMarshaller() throws JAXBException {
if (jaxbContext==null) {
jaxbContext=JAXBContext.newInstance("org.apache.juddi.api_v3");
}
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
return marshaller;
}
private String toString(final EntityMappings entityMappings) throws JAXBException {
final JAXBContext entityMappingsContext = JAXBContextFactory.newInstance(EntityMappings.class);
final Marshaller marshaller = entityMappingsContext.createMarshaller();
marshaller.setProperty("jaxb.formatted.output", true);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
marshaller.marshal(entityMappings, baos);
final String actual = new String(baos.toByteArray());
return actual.trim();
}
private static <T> Marshaller createXmlMarshaller(T object, boolean doFormatting, Class<?>... nestedClasses) throws JAXBException {
Class<?>[] targetClasses = merge(object.getClass(), nestedClasses);
JAXBContext jc = createJAXBContext(targetClasses);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, doFormatting);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
logger.debug("Using Marshaller of type: " + marshaller.getClass().getName());
XmlFormat format = XmlFormat.resolveFromClazz(object.getClass());
if(format != null && !format.equals(XmlFormat.UNKNOWN)) {
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, format.xsiSchemaLocation);
}
logger.debug(marshaller.getClass().getCanonicalName());
return marshaller;
}
@Override
public void writeTo(OutputStream out) throws IOException{
try{
Marshaller m = context.createMarshaller();
if(format)
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(bean, out);
}catch(JAXBException ex){
throw new IOException(ex);
}
}
private Marshaller getMarshaller() throws JAXBException {
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, getSafeEncoding());
return marshaller;
}
/**
* Writes the given bean to the given output stream.
* @param bean the bean to write.
* @param os the output stream to write to.
* @param fragment whether the {@code <?xml ... ?>} header should be
* included. The header is not included if the bean is just an
* XML fragment encapsulated in a higher level XML element.
* @throws JAXBException An XML Binding exception occurred.
**/
private static void writeXml(Object bean, OutputStream os, boolean fragment)
throws JAXBException {
final Marshaller m = createMarshaller();
if (fragment) m.setProperty(m.JAXB_FRAGMENT,Boolean.TRUE);
m.marshal(bean,os);
}
/**
* Serializes an Object to JSON and writes it using the writer provided
*
* @param object
* Object to write as JSON, which must have a no-arg constructor.
* @param jsonfile
* BufferedWriter to write JSON Object into
* @throws JAXBException
*/
public static void writeObjectAsJSON(Object object, BufferedWriter jsonfile) throws JAXBException {
JAXBContext jc = JAXBContextFactory.createContext(new Class[] { object.getClass(), ObjectFactory.class }, null);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
marshaller.marshal(object, jsonfile);
}