下面列出了怎么用javax.xml.bind.Marshaller的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public <T> T readPayloadAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
JAXBResult out = new JAXBResult(unmarshaller);
// since the bridge only produces fragments, we need to fire start/end document.
try {
out.getHandler().startDocument();
if (rawContext != null) {
Marshaller m = rawContext.createMarshaller();
m.setProperty("jaxb.fragment", Boolean.TRUE);
m.marshal(jaxbObject,out);
} else
bridge.marshal(jaxbObject,out);
out.getHandler().endDocument();
} catch (SAXException e) {
throw new JAXBException(e);
}
return (T)out.getResult();
}
/**
* object -> xml
*
* @param object
* @param childClass
*/
public static String marshal(Object object) {
if (object == null) {
return null;
}
try {
JAXBContext jaxbCtx = JAXBContext.newInstance(object.getClass());
Marshaller marshaller = jaxbCtx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
StringWriter sw = new StringWriter();
marshaller.marshal(object, sw);
return sw.toString();
} catch (Exception e) {
}
return null;
}
/**
* Creates an configures a new JAXB marshaller.
* This method is invoked only when no existing marshaller is available in the pool.
* Subclasses can override this method if they need to change the marshaller configuration.
*
* @return a new marshaller configured for formatting OGC/ISO XML.
* @throws JAXBException if an error occurred while creating and configuring the marshaller.
*
* @see #context
* @see #acquireMarshaller()
*/
protected Marshaller createMarshaller() throws JAXBException {
final Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
/*
* Note: we do not set the Marshaller.JAXB_ENCODING property because specification
* said that the default value is "UTF-8", which is what we want.
*/
String key;
if ((key = implementation.indentKey) != null) {
marshaller.setProperty(key, CharSequences.spaces(Constants.DEFAULT_INDENTATION));
}
synchronized (replacements) {
for (final AdapterReplacement adapter : replacements) {
adapter.register(marshaller);
}
}
return marshaller;
}
@Test
public void testNamespaceConversion() throws Exception {
W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
JAXBContext context = JAXBContext.newInstance(TestBean.class);
Marshaller m = context.createMarshaller();
Map<String, String> outMap = new HashMap<>();
outMap.put("{http://testbeans.com}testBean", "{http://testbeans.com/v2}testBean");
outMap.put("{http://testbeans.com}bean", "{http://testbeans.com/v3}bean");
OutTransformWriter transformWriter = new OutTransformWriter(writer,
outMap,
Collections.<String, String>emptyMap(),
Collections.<String>emptyList(),
false,
"");
m.marshal(new TestBean(), transformWriter);
Element el = writer.getDocument().getDocumentElement();
assertEquals("http://testbeans.com/v2", el.getNamespaceURI());
assertFalse(StringUtils.isEmpty(el.getPrefix()));
Element el2 = DOMUtils.getFirstElement(el);
assertEquals("http://testbeans.com/v3", el2.getNamespaceURI());
assertFalse(StringUtils.isEmpty(el2.getPrefix()));
}
/**
* Marshal the provided object using the OutputStream specified
*
* @param objectToMarshal
* @param outputStream
* @throws JAXBException
*/
public static void marshal(Object objectToMarshal, OutputStream outputStream) throws JAXBException {
if (objectToMarshal != null) {
long startTime = System.currentTimeMillis();
JAXBContext context = JAXBContext.newInstance(objectToMarshal.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
marshaller.marshal(objectToMarshal, outputStream);
System.out.println("marshaled " + objectToMarshal.getClass() + " in: "
+ (System.currentTimeMillis() - startTime));
} else {
throw new IllegalArgumentException("Cannot marshal null object");
}
}
/**
* 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();
}
}
public synchronized void init() {
try{
URL url = Resources.getResource("com/iris/common/subsystem/care/behavior/behavior_catalog.xml");
JAXBContext context = JAXBContext.newInstance(BehaviorCatalog.class);
Marshaller m = context.createMarshaller();
BehaviorCatalog catalog = (BehaviorCatalog) context.createUnmarshaller().unmarshal(url);
behavior = catalog.getBehavior();
behaviorMap = new HashMap<String, BehaviorCatalog.BehaviorCatalogTemplate>(behavior.size());
for (BehaviorCatalogTemplate catTemplate : behavior){
behaviorMap.put(catTemplate.id, catTemplate);
}
}catch (Exception e){
throw new RuntimeException(e);
}
}
/**
* Object to XML
* @param object object
* @return xml
*/
public static String convertToXML(Object object){
try {
Map<Class<?>, Marshaller> mMap = mMapLocal.get();
if(!mMap.containsKey(object.getClass())){
JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//设置CDATA输出字符
marshaller.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() {
public void escape(char[] ac, int i, int j, boolean flag, Writer writer) throws IOException {
writer.write(ac, i, j);
}
});
mMap.put(object.getClass(), marshaller);
}
StringWriter stringWriter = new StringWriter();
mMap.get(object.getClass()).marshal(object,stringWriter);
return stringWriter.getBuffer().toString();
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
public static byte[] serialize(final StandardSnippet snippet) {
try {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final BufferedOutputStream bos = new BufferedOutputStream(baos);
JAXBContext context = JAXBContext.newInstance(StandardSnippet.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(snippet, bos);
bos.flush();
return baos.toByteArray();
} catch (final IOException | JAXBException e) {
throw new FlowSerializationException(e);
}
}
protected String marshall(Object result, MediaType mediaType) throws Throwable {
if (null != mediaType && mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
JSONProvider jsonProvider = (JSONProvider) super.getApplicationContext().getBean("jsonProvider");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
jsonProvider.writeTo(result, result.getClass().getGenericSuperclass(),
result.getClass().getAnnotations(), mediaType, null, baos);
return new String(baos.toByteArray(), "UTF-8");
} else {
JAXBContext context = JAXBContext.newInstance(result.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("com.sun.xml.bind.marshaller.CharacterEscapeHandler", new CDataCharacterEscapeHandler());
StringWriter writer = new StringWriter();
marshaller.marshal(result, writer);
return writer.toString();
}
}
/**
* 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 Marshaller createJaxbMarshaller() {
try {
final JAXBContext jaxbContext = createJAXBContext();
final Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
return jaxbMarshaller;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param object 对象
* @return 返回xmlStr
* @throws UtilException
*/
public static String object2Xml(final Object object) throws UtilException {
try {
JAXBContext context = JAXBContext.newInstance(object.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化输出
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // 编码格式,默认为utf-8o
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // 是否省略xml头信息
Writer writer = new CharArrayWriter();
XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(writer);
xmlStreamWriter.writeStartDocument((String) marshaller.getProperty(Marshaller.JAXB_ENCODING), "1.0");
marshaller.marshal(object, xmlStreamWriter);
xmlStreamWriter.writeEndDocument();
xmlStreamWriter.close();
String xml = writer.toString();
xml = StringUtils.replace(xml, "<", "<");
xml = StringUtils.replace(xml, ">", ">");
xml = StringUtils.replace(xml, "&", "&");
xml = StringUtils.replace(xml, "
", GlobalConstants.BLANK);
return xml;
}
catch (Exception e) {
throw new UtilException(ErrorCodeDef.XML_TRANS_ERROR, e);
}
}
public Entry<String, String> serializeForType(HttpServletRequest request, Response resp) {
String format = getStringParameter(request, "f", "xml");
String jsonpCallback = request.getParameter("callback");
boolean json = "json".equals(format);
boolean jsonp = "jsonp".equals(format) && jsonpCallback != null;
Marshaller marshaller;
MediaType type;
if (json) {
marshaller = createJsonMarshaller();
type = MediaType.JSON_UTF_8;
} else if (jsonp) {
marshaller = createJsonMarshaller();
type = MediaType.JAVASCRIPT_UTF_8;
} else {
marshaller = createXmlMarshaller();
type = MediaType.XML_UTF_8;
}
StringWriter writer = new StringWriter();
try {
if (jsonp) {
writer.append(jsonpCallback).append('(');
}
marshaller.marshal(new ObjectFactory().createSubsonicResponse(resp), writer);
if (jsonp) {
writer.append(");");
}
} catch (JAXBException x) {
LOG.error("Failed to marshal JAXB", x);
throw new RuntimeException(x);
}
return Pair.of(type.toString(), writer.toString());
}
@Test
public void buildsMarshallerWithJAXBEncodingProperty() throws Exception {
JAXBContextFactory factory =
new JAXBContextFactory.Builder().withMarshallerJAXBEncoding("UTF-16").build();
Marshaller marshaller = factory.createMarshaller(Object.class);
assertEquals("UTF-16", marshaller.getProperty(Marshaller.JAXB_ENCODING));
}
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);
}
}
public void marshal(Marshaller m, Object object, Node output) throws JAXBException {
m.setProperty(Marshaller.JAXB_FRAGMENT,true);
try {
m.marshal(object,output);
} finally {
m.setProperty(Marshaller.JAXB_FRAGMENT,false);
}
}
@Override
public Document asXML() throws JDOMException, IOException, SAXParseException {
JDOMResult result = new JDOMResult();
try {
Marshaller marshaller = getMarshaller();
marshaller.marshal(jaxbObject, result);
} catch (JAXBException e) {
throw new IOException(e);
}
return result.getDocument();
}
/**
* Sends the given MMI event to JVoiceXML.
* @param request the event to send.
* @throws IOException
* error sending
* @throws JAXBException
* error marshalling the event
* @throws URISyntaxException
* error determining the source attribute
*/
public final void send(final LifeCycleEvent request)
throws IOException, JAXBException,
URISyntaxException {
event = null;
final Socket client = new Socket("localhost", 4343);
request.setSource(source.toString());
final URI target = TcpUriFactory.createUri(
(InetSocketAddress) client.getRemoteSocketAddress());
request.setTarget(target.toString());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
client.close();
return;
}
final JAXBContext ctx = JAXBContext.newInstance(Mmi.class);
final Marshaller marshaller = ctx.createMarshaller();
final OutputStream out = client.getOutputStream();
marshaller.marshal(request, out);
LOGGER.info("sent '" + request + "'");
client.close();
if ((request instanceof StartRequest)
|| (request instanceof PrepareRequest)) {
clearedContext = false;
}
}
@Test
public void marshallClassCastExceptionTest() throws Exception {
JAXBContext jaxbContext;
Marshaller marshaller;
URLClassLoader jaxbContextClassLoader;
// Generate java classes by xjc
runXjc(XSD_FILENAME);
// Compile xjc generated java files
compileXjcGeneratedClasses();
// Create JAXB context based on xjc generated package.
// Need to create URL class loader ot make compiled classes discoverable
// by JAXB context
jaxbContextClassLoader = URLClassLoader.newInstance(new URL[] {testWorkDirUrl});
jaxbContext = JAXBContext.newInstance( TEST_PACKAGE, jaxbContextClassLoader);
// Create instance of Xjc generated data type.
// Java classes were compiled during the test execution hence reflection
// is needed here
Class classLongListClass = jaxbContextClassLoader.loadClass(TEST_CLASS);
Object objectLongListClass = classLongListClass.newInstance();
// Get 'getIn' method object
Method getInMethod = classLongListClass.getMethod( GET_LIST_METHOD, (Class [])null );
// Invoke 'getIn' method
List<Long> inList = (List<Long>)getInMethod.invoke(objectLongListClass);
// Add values into the jaxb object list
inList.add(Long.valueOf(0));
inList.add(Long.valueOf(43));
inList.add(Long.valueOf(1000000123));
// Marshall constructed complex type variable to standard output.
// In case of failure the ClassCastException will be thrown
marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(objectLongListClass, System.out);
}
/**
* @param instance オブジェクト
* @param outputStream XML出力ストリーム
* @throws IOException IO上の問題があったとき投げられる例外
* @throws JAXBException JAXB上の問題があったとき投げられる例外
*/
public static void marshal(
final Object instance,
final OutputStream outputStream) throws IOException, JAXBException {
Marshaller m = context.createMarshaller();
m.marshal(instance, outputStream);
}
/**
* Converts the given {@link Throwable} into an XML representation
* and put that as a DOM tree under the given node.
*/
public static void marshal( Throwable t, Node parent ) throws JAXBException {
Marshaller m = JAXB_CONTEXT.createMarshaller();
try {
m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper",nsp);
} catch (PropertyException pe) {}
m.marshal(new ExceptionBean(t), parent );
}
public static String marshal(Object obj) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, CHARSET_NAME);
StringWriter writer = new StringWriter();
try{
jaxbMarshaller.marshal(obj, writer);
return writer.toString();
} finally {
IoUtils.closeQuietly(writer);
}
}
public String marshalObject(ModelObject object, ModuleType... moduleTypes) {
String result = null;
try (ByteArrayOutputStream out = new ByteArrayOutputStream(1024)) {
CityGMLNamespaceContext ctx = new CityGMLNamespaceContext();
for (ModuleType moduleType : moduleTypes)
ctx.setPrefix(cityGMLVersion.getModule(moduleType));
saxWriter.setOutput(out);
saxWriter.setNamespaceContext(ctx);
Marshaller marshaller = cityGMLBuilder.getJAXBContext().createMarshaller();
JAXBElement<?> jaxbElement = jaxbMarshaller.marshalJAXBElement(object);
if (jaxbElement != null)
marshaller.marshal(jaxbElement, saxWriter);
saxWriter.flush();
result = out.toString();
out.reset();
} catch (JAXBException | IOException | SAXException e) {
//
} finally {
saxWriter.reset();
}
return result;
}
public final void marshal(T object,XMLStreamWriter output, AttachmentMarshaller am) throws JAXBException {
Marshaller m = context.marshallerPool.take();
m.setAttachmentMarshaller(am);
marshal(m,object,output);
m.setAttachmentMarshaller(null);
context.marshallerPool.recycle(m);
}
/**
* @since 2.0.2
*/
public final void marshal(T object, ContentHandler contentHandler, AttachmentMarshaller am) throws JAXBException {
Marshaller m = context.marshallerPool.take();
m.setAttachmentMarshaller(am);
marshal(m,object,contentHandler);
m.setAttachmentMarshaller(null);
context.marshallerPool.recycle(m);
}
public void marshal(Marshaller m, Object object, Node output) throws JAXBException {
m.setProperty(Marshaller.JAXB_FRAGMENT,true);
try {
m.marshal(object,output);
} finally {
m.setProperty(Marshaller.JAXB_FRAGMENT,false);
}
}
/**
* Initialize JAXB transformers
*
* @throws JAXBException
*/
private void initJAXB() throws JAXBException {
if (marshaller != null) {
return ;
}
JAXBContext jaxbContext = getPspipJaxb();
marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
unmarshaller = jaxbContext.createUnmarshaller();
}
JsonProviderPrototypeServiceFactory(
Dictionary<String, ?> properties,
Optional<TypeConverter> typeConverter,
Optional<Marshaller.Listener> marshallerListener,
Optional<Unmarshaller.Listener> unmarshallerListener,
Optional<SchemaHandler> schemaHandler
) {
_properties = properties;
_typeConverter = typeConverter;
_marshallerListener = marshallerListener;
_unmarshallerListener = unmarshallerListener;
_schemaHandler = schemaHandler;
}
public void marshal(Marshaller m, Object object, Node output) throws JAXBException {
m.setProperty(Marshaller.JAXB_FRAGMENT,true);
try {
m.marshal(object,output);
} finally {
m.setProperty(Marshaller.JAXB_FRAGMENT,false);
}
}