當前位置: 首頁>>代碼示例>>Java>>正文


Java Marshaller類代碼示例

本文整理匯總了Java中javax.xml.bind.Marshaller的典型用法代碼示例。如果您正苦於以下問題:Java Marshaller類的具體用法?Java Marshaller怎麽用?Java Marshaller使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Marshaller類屬於javax.xml.bind包,在下文中一共展示了Marshaller類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: obj2xml

import javax.xml.bind.Marshaller; //導入依賴的package包/類
/**
 * 對象轉為xml字符串
 * 
 * @param obj
 * @param isFormat
 *            true即按標簽自動換行,false即是一行的xml
 * @param includeHead
 *            true則包含xm頭聲明信息,false則不包含
 * @return
 */
public String obj2xml(Object obj, boolean isFormat, boolean includeHead) {
	try (StringWriter writer = new StringWriter()) {
		Marshaller m = MARSHALLERS.get(obj.getClass());
		if (m == null) {
			m = JAXBContext.newInstance(obj.getClass()).createMarshaller();
			m.setProperty(Marshaller.JAXB_ENCODING, I18NConstants.DEFAULT_CHARSET);
		}
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, isFormat);
		m.setProperty(Marshaller.JAXB_FRAGMENT, !includeHead);// 是否省略xm頭聲明信息
		m.marshal(obj, writer);
		return writer.toString();
	} catch (Exception e) {
		throw new ZhhrException(e.getMessage(), e);
	}
}
 
開發者ID:wooui,項目名稱:springboot-training,代碼行數:26,代碼來源:XMLUtil.java

示例2: saveSaas

import javax.xml.bind.Marshaller; //導入依賴的package包/類
public static void saveSaas(Saas saas, FileObject file) throws IOException, JAXBException {
    JAXBContext jc = JAXBContext.newInstance(SaasServices.class.getPackage().getName());
    Marshaller marshaller = jc.createMarshaller();
    JAXBElement<SaasServices> jbe = new JAXBElement<SaasServices>(QNAME_SAAS_SERVICES, SaasServices.class, saas.getDelegate());
    OutputStream out = null;
    FileLock lock = null;
    try {
        lock = file.lock();
        out = file.getOutputStream(lock);
        marshaller.marshal(jbe, out);
    } finally {
        if (out != null) {
            out.close();
        }
        if (lock != null) {
            lock.releaseLock();
        }
    }
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:20,代碼來源:SaasUtil.java

示例3: save

import javax.xml.bind.Marshaller; //導入依賴的package包/類
/**
 * Save.
 *
 * @param file2Save the file2 save
 * @return true, if successful
 */
public boolean save(File file2Save) {
	
	boolean saved = true;
	try {			
		JAXBContext pc = JAXBContext.newInstance(this.getClass()); 
		Marshaller pm = pc.createMarshaller(); 
		pm.setProperty( Marshaller.JAXB_ENCODING, "UTF-8" );
		pm.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); 

		Writer pw = new FileWriter(file2Save);
		pm.marshal(this, pw);
		pw.close();

	} catch (Exception e) {
		System.out.println("XML-Error while saving Setup-File!");
		e.printStackTrace();
		saved = false;
	}		
	return saved;		
}
 
開發者ID:EnFlexIT,項目名稱:AgentWorkbench,代碼行數:27,代碼來源:ThreadProtocol.java

示例4: toXmlWithComment

import javax.xml.bind.Marshaller; //導入依賴的package包/類
public static String toXmlWithComment(Object obj, String tagName, String comment) {
    StringWriter writer = new StringWriter();
    String res = null;
    try {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(obj, writer);

        String xml = writer.toString();

        if (xml.indexOf(tagName) > -1)
            res = xml.replace("<" + tagName + ">", "<!--" + comment + "-->\n" + "<" + tagName + ">");
        else
            res = xml;

    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return res;
}
 
開發者ID:avedensky,項目名稱:JavaRushTasks,代碼行數:22,代碼來源:Solution.java

示例5: saveEntryDataToFile

import javax.xml.bind.Marshaller; //導入依賴的package包/類
public void saveEntryDataToFile(File f) {
	try {
		JAXBContext context = JAXBContext.newInstance(EntryListWrapper.class);
		Marshaller m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		
		// wrapping the entry data
		EntryListWrapper wrapper = new EntryListWrapper();
		wrapper.setEntries(entryList);
		
		// marshalling and saving xml to file
		m.marshal(wrapper, f);
		
		// save file path
		setFilePath(f);
	}
	catch (Exception e) {
		Alert alert = new Alert(AlertType.ERROR);
		alert.setTitle("Error");
		alert.setHeaderText("Could not save data");
		alert.setContentText("Could not save data to file:\n" + f.getPath());
		
		alert.showAndWait();
	}
}
 
開發者ID:yc45,項目名稱:kanphnia2,代碼行數:26,代碼來源:MainApp.java

示例6: generateDetailedReportMultiSignatures

import javax.xml.bind.Marshaller; //導入依賴的package包/類
@Test
public void generateDetailedReportMultiSignatures() throws Exception {
	JAXBContext context = JAXBContext.newInstance(DetailedReport.class.getPackage().getName());
	Unmarshaller unmarshaller = context.createUnmarshaller();
	Marshaller marshaller = context.createMarshaller();

	DetailedReport detailedReport = (DetailedReport) unmarshaller.unmarshal(new File("src/test/resources/detailed-report-multi-signatures.xml"));
	assertNotNull(detailedReport);

	StringWriter writer = new StringWriter();
	marshaller.marshal(detailedReport, writer);

	String htmlDetailedReport = service.generateDetailedReport(writer.toString());
	assertTrue(Utils.isStringNotEmpty(htmlDetailedReport));
	logger.debug("Detailed report html : " + htmlDetailedReport);
}
 
開發者ID:esig,項目名稱:dss-demonstrations,代碼行數:17,代碼來源:XSLTServiceTest.java

示例7: JAXBSource

import javax.xml.bind.Marshaller; //導入依賴的package包/類
/**
 * Creates a new {@link javax.xml.transform.Source} for the given content object.
 *
 * @param   marshaller
 *      A marshaller instance that will be used to marshal
 *      <code>contentObject</code> into XML. This must be
 *      created from a JAXBContext that was used to build
 *      <code>contentObject</code> and must not be null.
 * @param   contentObject
 *      An instance of a JAXB-generated class, which will be
 *      used as a {@link javax.xml.transform.Source} (by marshalling it into XML).  It must
 *      not be null.
 * @throws JAXBException if an error is encountered while creating the
 * JAXBSource or if either of the parameters are null.
 */
public JAXBSource( Marshaller marshaller, Object contentObject )
    throws JAXBException {

    if( marshaller == null )
        throw new JAXBException(
            Messages.format( Messages.SOURCE_NULL_MARSHALLER ) );

    if( contentObject == null )
        throw new JAXBException(
            Messages.format( Messages.SOURCE_NULL_CONTENT ) );

    this.marshaller = marshaller;
    this.contentObject = contentObject;

    super.setXMLReader(pseudoParser);
    // pass a dummy InputSource. We don't care
    super.setInputSource(new InputSource());
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:34,代碼來源:JAXBSource.java

示例8: readPayload

import javax.xml.bind.Marshaller; //導入依賴的package包/類
@Override
public XMLStreamReader readPayload() throws XMLStreamException {
   try {
        if(infoset==null) {
                            if (rawContext != null) {
                    XMLStreamBufferResult sbr = new XMLStreamBufferResult();
                                    Marshaller m = rawContext.createMarshaller();
                                    m.setProperty("jaxb.fragment", Boolean.TRUE);
                                    m.marshal(jaxbObject, sbr);
                    infoset = sbr.getXMLStreamBuffer();
                            } else {
                                MutableXMLStreamBuffer buffer = new MutableXMLStreamBuffer();
                                writePayloadTo(buffer.createFromXMLStreamWriter());
                                infoset = buffer;
                            }
        }
        XMLStreamReader reader = infoset.readAsXMLStreamReader();
        if(reader.getEventType()== START_DOCUMENT)
            XMLStreamReaderUtil.nextElementContent(reader);
        return reader;
    } catch (JAXBException e) {
       // bug 6449684, spec 4.3.4
       throw new WebServiceException(e);
    }
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:26,代碼來源:JAXBMessage.java

示例9: readPayloadAsJAXB

import javax.xml.bind.Marshaller; //導入依賴的package包/類
@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();
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:19,代碼來源:JAXBMessage.java

示例10: readPayloadElement

import javax.xml.bind.Marshaller; //導入依賴的package包/類
private void readPayloadElement() {
    PayloadElementSniffer sniffer = new PayloadElementSniffer();
    try {
        if (rawContext != null) {
            Marshaller m = rawContext.createMarshaller();
            m.setProperty("jaxb.fragment", Boolean.FALSE);
            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.
        payloadQName = sniffer.getPayloadQName();
    }
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:22,代碼來源:JAXBDispatchMessage.java

示例11: createMarshaller

import javax.xml.bind.Marshaller; //導入依賴的package包/類
/**
 * 創建Marshaller並設定encoding(可為null). 線程不安全,需要每次創建或pooling。
 */
@SuppressWarnings("rawtypes")
public static Marshaller createMarshaller(Class clazz, String encoding) {
	try {
		JAXBContext jaxbContext = getJaxbContext(clazz);

		Marshaller marshaller = jaxbContext.createMarshaller();

		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

		if (StringUtils.isNotBlank(encoding)) {
			marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
		}

		return marshaller;
	} catch (JAXBException e) {
		throw ExceptionUtil.unchecked(e);
	}
}
 
開發者ID:zhangjunfang,項目名稱:util,代碼行數:22,代碼來源:XmlMapper.java

示例12: serializeBillingDetails

import javax.xml.bind.Marshaller; //導入依賴的package包/類
private void serializeBillingDetails(BillingResult billingResult,
        BillingDetailsType billingDetails) {

    try {
        final JAXBContext context = JAXBContext
                .newInstance(BillingdataType.class);
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty("jaxb.formatted.output", Boolean.FALSE);
        final BillingdataType billingdataType = new BillingdataType();
        billingdataType.getBillingDetails().add(billingDetails);
        marshaller.marshal(factory.createBillingdata(billingdataType), out);
        final String xml = new String(out.toByteArray(), "UTF-8");
        billingResult.setResultXML(xml.substring(
                xml.indexOf("<Billingdata>") + 13,
                xml.indexOf("</Billingdata>")).trim());
        billingResult.setGrossAmount(billingDetails.getOverallCosts()
                .getGrossAmount());
        billingResult.setNetAmount(billingDetails.getOverallCosts()
                .getNetAmount());
    } catch (JAXBException | UnsupportedEncodingException ex) {
        throw new BillingRunFailed(ex);
    }
}
 
開發者ID:servicecatalog,項目名稱:oscm,代碼行數:25,代碼來源:RevenueCalculatorBean.java

示例13: serialize

import javax.xml.bind.Marshaller; //導入依賴的package包/類
@Override
public void serialize(final T t, final OutputStream out) throws SerializationException {
    if (t == null) {
        throw new IllegalArgumentException("The object to serialize cannot be null");
    }

    if (out == null) {
        throw new IllegalArgumentException("OutputStream cannot be null");
    }

    try {
        final Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(t, out);
    } catch (JAXBException e) {
        throw new SerializationException("Unable to serialize object", e);
    }
}
 
開發者ID:apache,項目名稱:nifi-registry,代碼行數:19,代碼來源:JAXBSerializer.java

示例14: toXML

import javax.xml.bind.Marshaller; //導入依賴的package包/類
@Override
public String toXML(T obj) {

    try {
        JAXBContext context = JAXBContext.newInstance(type);

        Marshaller m = context.createMarshaller();
        if(schemaLocation != null) {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            StreamSource source = new StreamSource(getClass().getResourceAsStream(schemaLocation));
            Schema schema = schemaFactory.newSchema(source);
            m.setSchema(schema);
        }

        StringWriter writer = new StringWriter();

        m.marshal(obj, writer);
        String xml = writer.toString();

        return xml;
    } catch (Exception e) {
        System.out.println("ERROR: "+e.toString());
        return null;
    }
}
 
開發者ID:arcuri82,項目名稱:testing_security_development_enterprise_systems,代碼行數:27,代碼來源:ConverterImpl.java

示例15: createLtiOutcomesRequest

import javax.xml.bind.Marshaller; //導入依賴的package包/類
private Request createLtiOutcomesRequest(ImsxPOXEnvelopeType imsxEnvelope, String url, String consumerKey,
	String consumerSecret) throws Exception
{
	final Request webRequest = new Request(url);
	webRequest.setMethod(Method.POST);
	webRequest.setMimeType("application/xml");

	final ObjectFactory of = new ObjectFactory();
	final JAXBElement<ImsxPOXEnvelopeType> createImsxPOXEnvelopeRequest = of
		.createImsxPOXEnvelopeRequest(imsxEnvelope);

	final JAXBContext jc = JAXBContext.newInstance("com.tle.web.lti.imsx", LtiServiceImpl.class.getClassLoader());
	final Marshaller marshaller = jc.createMarshaller();
	marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

	final StringWriter sw = new StringWriter();
	marshaller.marshal(createImsxPOXEnvelopeRequest, sw);
	webRequest.setBody(sw.toString());

	final String bodyHash = calcSha1Hash(webRequest.getBody());
	final OAuthMessage message = createLaunchParameters(consumerKey, consumerSecret, url, bodyHash);
	webRequest.addHeader("Authorization", message.getAuthorizationHeader(""));
	return webRequest;
}
 
開發者ID:equella,項目名稱:Equella,代碼行數:25,代碼來源:LtiServiceImpl.java


注:本文中的javax.xml.bind.Marshaller類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。