Java Code Examples for javax.xml.bind.Marshaller#marshal()

The following examples show how to use javax.xml.bind.Marshaller#marshal() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JAXBDispatchMessage.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example 2
Source File: JAXBDispatchMessage.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example 3
Source File: XmlMultiConfiguration.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private XmlMultiConfiguration(Map<String, Config> configurations) {
  try {
    Schema schema = discoverSchema(new StreamSource(CORE_SCHEMA_URL.openStream()), new StreamSource(MULTI_SCHEMA_URL.openStream()));

    this.configurations = configurations;

    ObjectFactory objectFactory = new ObjectFactory();
    Configurations jaxb = objectFactory.createConfigurations().withConfiguration(configurations.entrySet().stream().map(
      entry -> entry.getValue().unparse(objectFactory, objectFactory.createConfigurationsConfiguration().withIdentity(entry.getKey()))).collect(toList()));

    JAXBContext jaxbContext = JAXBContext.newInstance(Configurations.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setSchema(schema);

    this.document = documentBuilder(schema).newDocument();
    marshaller.marshal(jaxb, document);
    this.renderedDocument = documentToText(document);
  } catch (JAXBException | IOException | TransformerException | ParserConfigurationException | SAXException e) {
    throw new XmlConfigurationException(e);
  }
}
 
Example 4
Source File: KmlExporter.java    From importer-exporter with Apache License 2.0 6 votes vote down vote up
private void addBorder(BoundingBox tile, StyleType style, SAXWriter saxWriter) throws JAXBException {
	Marshaller marshaller = jaxbKmlContext.createMarshaller();
	marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

	PlacemarkType placemark = kmlFactory.createPlacemarkType();
	placemark.setName("Tile border");
	LineStringType lineString = kmlFactory.createLineStringType();
	lineString.setTessellate(true);
	lineString.getCoordinates().add(tile.getLowerCorner().getX() + "," + tile.getLowerCorner().getY());
	lineString.getCoordinates().add(tile.getUpperCorner().getX() + "," + tile.getLowerCorner().getY());
	lineString.getCoordinates().add(tile.getUpperCorner().getX() + "," + tile.getUpperCorner().getY());
	lineString.getCoordinates().add(tile.getLowerCorner().getX() + "," + tile.getUpperCorner().getY());
	lineString.getCoordinates().add(tile.getLowerCorner().getX() + "," + tile.getLowerCorner().getY());
	placemark.setAbstractGeometryGroup(kmlFactory.createLineString(lineString));

	if (style != null) {
		placemark.setStyleUrl("#" + style.getId());
		marshaller.marshal(kmlFactory.createStyle(style), saxWriter);
	}

	marshaller.marshal(kmlFactory.createPlacemark(placemark), saxWriter);
}
 
Example 5
Source File: JAXBRMRoundTripTest.java    From archie with Apache License 2.0 5 votes vote down vote up
@Test
public void dataValues() throws Exception {
    archetype = parser.parse(JAXBRMRoundTripTest.class.getResourceAsStream("/com/nedap/archie/json/openEHR-EHR-CLUSTER.datavalues.v1.adls"));
    Cluster cluster =  (Cluster) testUtil.constructEmptyRMObject(archetype.getDefinition());
    RMQueryContext queryContext = new RMQueryContext(cluster);
    DvText text = queryContext.find("/items['Text']/value");
    text.setValue("test-text");
    DvQuantity quantity = queryContext.find("/items['Quantity']/value");
    quantity.setMagnitude(23d);
    DvDate date = queryContext.find("/items['Date']/value");
    date.setValue(LocalDate.of(2016, 1, 1));

    DvDateTime datetime = queryContext.find("/items['Datetime']/value");
    datetime.setValue(LocalDateTime.of(2016, 1, 1, 12, 00));

    DvTime time = queryContext.find("/items['Time']/value");
    time.setValue(LocalTime.of(12, 0));

    StringWriter writer = new StringWriter();
    Marshaller marshaller = JAXBUtil.getArchieJAXBContext().createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(cluster, writer);
    String xml = writer.toString();
    assertThat(xml, containsString(">12:00<"));
    assertThat(xml, containsString(">2016-01-01T12:00<"));
    assertThat(xml, containsString(">2016-01-01<"));

    System.out.println(xml);

    //now parse again
    Cluster parsedCluster = (Cluster) JAXBUtil.getArchieJAXBContext().createUnmarshaller().unmarshal(new StringReader(writer.toString()));
    RMQueryContext parsedQueryContext = new RMQueryContext(parsedCluster);
    
    assertThat(parsedQueryContext.<DvText>find("/items['Text']/value").getValue(), is("test-text"));
    assertThat(parsedQueryContext.<DvDate>find("/items['Date']/value").getValue(), is(LocalDate.of(2016, 1, 1)));
    assertThat(parsedQueryContext.<DvDateTime>find("/items['Datetime']/value").getValue(), is(LocalDateTime.of(2016, 1, 1, 12, 00)));
    assertThat(parsedQueryContext.<DvTime>find("/items['Time']/value").getValue(), is(LocalTime.of(12, 0)));
    assertEquals("double should be correct", parsedQueryContext.find("/items['Quantity']/value/magnitude"), 23d, 0.001d);
}
 
Example 6
Source File: MpOwnerShareResultAssemblerTest.java    From development with Apache License 2.0 5 votes vote down vote up
private String serialize(Object jaxbTree) throws JAXBException,
        PropertyException {
    JAXBContext jc = JAXBContext.newInstance(jaxbTree.getClass());
    System.out.println(jc.getClass().getCanonicalName());
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    marshaller.marshal(jaxbTree, bos);
    String xmlAsString = Strings.toString(bos.toByteArray());
    return xmlAsString;
}
 
Example 7
Source File: ObjectMapperHelpers.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
/**
 * Transforms an annotated Object to a XML string using javax.xml.bind.Marshaller
 *
 * @param object to transform to a XML String
 * @return a XML string representing the object
 * @throws IOException if is not possible to parse the object
 */
public static String ObjectToXml(Object object) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
    Marshaller marshaller = jaxbContext.createMarshaller();
    StringWriter sw = new StringWriter();
    marshaller.marshal(object, sw);
    return sw.toString();
}
 
Example 8
Source File: ReportTypes.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] toXmlByteArray() throws IOException, JAXBException {
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   JAXBContext jaxbContext = JAXBContext.newInstance(ReportTypes.class);
   Marshaller marshaller = jaxbContext.createMarshaller();
   marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
   marshaller.marshal(this, (OutputStream)bos);
   bos.close();
   return bos.toByteArray();
}
 
Example 9
Source File: MemberSubmissionEndpointReference.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void writeTo(Result result) {
    try {
        Marshaller marshaller = MemberSubmissionEndpointReference.msjc.get().createMarshaller();
        //marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.marshal(this, result);
    } catch (JAXBException e) {
        throw new WebServiceException("Error marshalling W3CEndpointReference. ", e);
    }
}
 
Example 10
Source File: WalkerData.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
public void writeXml(int worldId) {
	Schema schema = null;
	SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

	try {
		schema = sf.newSchema(new File("./data/static_data/npc_walker/npc_walker.xsd"));
	}
	catch (SAXException e1) {
		log.error("Error while saving data: " + e1.getMessage(), e1.getCause());
		return;
	}

	File xml = new File("./data/static_data/npc_walker/walker_" + worldId + "_" + World.getInstance().getWorldMap(worldId).getName() + ".xml");
	JAXBContext jc;
	Marshaller marshaller;
	try {
		jc = JAXBContext.newInstance(WalkerData.class);
		marshaller = jc.createMarshaller();
		marshaller.setSchema(schema);
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.marshal(this, xml);
	}
	catch (JAXBException e) {
		log.error("Error while saving data: " + e.getMessage(), e.getCause());
		return;
	}
}
 
Example 11
Source File: MarshallerBridge.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void marshal(Marshaller m, Object object, Result result) throws JAXBException {
    m.setProperty(Marshaller.JAXB_FRAGMENT,true);
    try {
        m.marshal(object,result);
    } finally {
        m.setProperty(Marshaller.JAXB_FRAGMENT,false);
    }
}
 
Example 12
Source File: CityGMLImportManager.java    From importer-exporter with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 13
Source File: JaxbUtils.java    From cherry with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 14
Source File: DBConnection.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
public String marshallIntoString() {
	try (StringWriter sw = new StringWriter()) {
		JAXBContext jaxbContext = JAXBContext.newInstance(DBConnection.class);
		Marshaller m = jaxbContext.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		m.marshal(this, sw);
		return sw.toString();
	} catch (JAXBException | IOException e) {
		return "";
	}
}
 
Example 15
Source File: JaxbOpenejb.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static <T> void marshal(final Class<T> type, final Object object, final OutputStream out) throws JAXBException {
    final JAXBContext jaxbContext = getContext(type);
    final Marshaller marshaller = jaxbContext.createMarshaller();

    marshaller.setProperty("jaxb.formatted.output", true);

    marshaller.marshal(object, out);
}
 
Example 16
Source File: CSVDBToXMLConverter.java    From ice with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * The all-powerful Main!
 * 
 * @param args
 * @throws IOException
 *             This exception will be thrown if main can't handle the files
 *             correctly. Mostly the CSV file.
 * @throws JAXBException
 *             This exception will be thrown if main can't handle the XML
 *             file.
 */
public static void main(String args[]) throws IOException, JAXBException {
	// Setup the file paths and readers
	String separator = System.getProperty("file.separator");
	String home = System.getProperty("user.home");
	File CSVFile = new File(home + separator + "ICETests" + separator
			+ "defaultMatDB.csv");
	File xmlFile = new File(home + separator + "ICETests" + separator
			+ "defaultMatDB.xml");
	FileReader reader = new FileReader(CSVFile);
	BufferedReader bufferedReader = new BufferedReader(reader);

	// Read the materials
	ArrayList<String> lines = new ArrayList<String>();
	String line;
	while ((line = bufferedReader.readLine()) != null) {
		lines.add(line);
	}

	// Close the readers
	bufferedReader.close();
	reader.close();

	// The first line is composed of the names of the properties.
	String[] propertyNames = lines.get(0).split(",");
	// Create a list to store all the materials
	ArrayList<Material> materials = new ArrayList<Material>();
	// Parse and create the materials
	for (int i = 1; i < lines.size(); i++) {
		String[] properties = lines.get(i).split(",");
		Material tmpMaterial = new Material();
		// The first property is the name
		tmpMaterial.setName(properties[0]);
		// All other properties are doubles with names equal to the same
		// index in the properties array.
		for (int j = 1; j < properties.length; j++) {
			tmpMaterial.setProperty(propertyNames[j],
					Double.valueOf(properties[j]));
		}

		// Add the material to the list
		materials.add(tmpMaterial);
	}

	// Note that none of the materials in this database have children. They
	// are all isotopes.

	// Create the list that will be written to XML.
	ICEList<Material> xmlList = new ICEList<Material>();
	xmlList.setList(materials);

	// Create the necessary JAXB equipment to dump the file
	JAXBContext jaxbContext = JAXBContext.newInstance(ICEList.class,
			Material.class);
	Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
	jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
	// Dump the file
	jaxbMarshaller.marshal(xmlList, xmlFile);
	
	return;
}
 
Example 17
Source File: ProductResourceTest.java    From oodt with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that {@link ProductResource product resources} are marshalled to
 * the expected XML format.
 * @throws IOException if the {@link Diff} constructor fails
 * @throws JAXBException if the {@link JAXBContext} or {@link Marshaller} fail
 * @throws MimeTypeException if {@link MimeTypes#forName(String)} fails
 * @throws SAXException if the {@link Diff} constructor fails
 */
@Test
public void testXmlMarshalling() throws IOException, JAXBException,
  MimeTypeException, SAXException
{
  // Create a ProductResource using ProductType, Reference, Metadata and
  // Product instances.
  Hashtable metadataEntries = new Hashtable<String, Object>();
  metadataEntries.put("CAS.Test", "test value");
  Metadata metadata = new Metadata();
  metadata.addMetadata(metadataEntries);

  Reference reference = new Reference("original", "dataStore", 1000,
    new MimeTypes().forName("text/plain"));
  List<Reference> references = new ArrayList<Reference>();
  references.add(reference);

  ProductType productType = new ProductType("1", "GenericFile", "test type",
    "repository", "versioner");

  Product product = new Product();
  product.setProductId("123");
  product.setProductName("test.txt");
  product.setProductStructure(Product.STRUCTURE_FLAT);
  product.setProductType(productType);

  ProductResource resource = new ProductResource(product, metadata,
    references, new File("/tmp"));


  // Generate the expected output.
  String expectedXml =
      "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
      + "<product>"
      + "<id>" + product.getProductId() + "</id>"
      + "<name>" + product.getProductName() + "</name>"
      + "<structure>" + product.getProductStructure() + "</structure>"
      + "<type>" + productType.getName() + "</type>"
      + "<metadata>"
      + "<keyval>"
      + "<key>" + metadata.getAllKeys().get(0) + "</key>"
      + "<val>" + metadata.getAllValues().get(0) + "</val>"
      + "</keyval>"
      + "</metadata>"
      + "<references>"
      + "<reference>"
      + "<productId>" + product.getProductId() + "</productId>"
      + "<refIndex>0</refIndex>"
      + "<dataStoreReference>"
      +    reference.getDataStoreReference()
      + "</dataStoreReference>"
      + "<originalReference>"
      +    reference.getOrigReference()
      + "</originalReference>"
      + "<mimeType>" + reference.getMimeType().getName() + "</mimeType>"
      + "<fileSize>" + reference.getFileSize() + "</fileSize>"
      + "</reference>"
      + "</references>"
      + "</product>";


  // Set up a JAXB context and marshall the ProductResource to XML.
  JAXBContext context = JAXBContext.newInstance(resource.getClass());
  Marshaller marshaller = context.createMarshaller();
  StringWriter writer = new StringWriter();
  marshaller.marshal(resource, writer);

  // Compare the expected and actual outputs.
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setIgnoreComments(true);
  XMLUnit.setIgnoreAttributeOrder(true);
  Diff diff = new Diff(expectedXml, writer.toString());
  assertTrue("The output XML was different to the expected XML: "
    + diff.toString(), diff.identical());
}
 
Example 18
Source File: CamelXmlHelper.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
/**
 * Dumps the definition as XML
 *
 * @param definition  the definition, such as a {@link org.apache.camel.NamedNode}
 * @param classLoader the class loader
 * @return the output in XML (is formatted)
 * @throws JAXBException is throw if error marshalling to XML
 */
public static String dumpModelAsXml(Object definition, ClassLoader classLoader, boolean includeEndTag, int indent) throws JAXBException, XMLStreamException {
    JAXBContext jaxbContext = JAXBContext.newInstance(JAXB_CONTEXT_PACKAGES, classLoader);

    StringWriter buffer = new StringWriter();

    // we do not want to output namespace
    XMLStreamWriter delegate = XMLOutputFactory.newInstance().createXMLStreamWriter(buffer);
    JaxbNoNamespaceWriter writer = new JaxbNoNamespaceWriter(delegate, indent);
    // we do not want to include the customId attribute
    writer.setSkipAttributes("customId");

    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "");
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(definition, writer);

    String answer = buffer.toString();

    // we can collapse <method> <tokenize> and <xtokenize> as they do not include a value
    answer = collapseNode(answer, "method");
    answer = collapseNode(answer, "tokenize");
    answer = collapseNode(answer, "xtokenize");

    // if there is only 1 element them collapse it, eg <log xxx></log> => <log xxx/>
    if (writer.getElements() == 1) {
        String token = "></" + writer.getRootElementName() + ">";
        answer = answer.replaceFirst(token, "/>");
    }

    if (!includeEndTag) {
        // remove last end tag
        int pos = answer.indexOf("</" + writer.getRootElementName() + ">");
        if (pos != -1) {
            answer = answer.substring(0, pos);
        }
        // and trim leading/ending spaces/newlines
        answer = answer.trim();
    }

    return answer;
}
 
Example 19
Source File: JAXBExtensionHelper.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void marshall(@SuppressWarnings("rawtypes") Class parent, QName qname,
                     ExtensibilityElement obj, PrintWriter pw,
                     final Definition wsdl, ExtensionRegistry registry) throws WSDLException {
    try {
        Marshaller u = createMarshaller();
        u.setProperty("jaxb.encoding", StandardCharsets.UTF_8.name());
        u.setProperty("jaxb.fragment", Boolean.TRUE);
        u.setProperty("jaxb.formatted.output", Boolean.TRUE);

        Object mObj = obj;

        Class<?> objectFactory = Class.forName(PackageUtils.getPackageName(typeClass) + ".ObjectFactory",
                                               true,
                                               obj.getClass().getClassLoader());
        Method[] methods = objectFactory.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getParameterTypes().length == 1
                && method.getParameterTypes()[0].equals(typeClass)) {

                mObj = method.invoke(objectFactory.newInstance(), new Object[] {obj});
            }
        }

        javax.xml.stream.XMLOutputFactory fact = javax.xml.stream.XMLOutputFactory.newInstance();
        XMLStreamWriter writer =
            new PrettyPrintXMLStreamWriter(fact.createXMLStreamWriter(pw), 2, getIndentLevel(parent));

        if (namespace != null && !namespace.equals(jaxbNamespace)) {
            Map<String, String> outMap = new HashMap<>();
            outMap.put("{" + jaxbNamespace + "}*", "{" + namespace + "}*");
            writer = new OutTransformWriter(writer,
                                            outMap,
                                            Collections.<String, String>emptyMap(),
                                            Collections.<String>emptyList(),
                                            false,
                                            "");
        }
        Map<String, String> nspref = new HashMap<>();
        for (Object ent : wsdl.getNamespaces().entrySet()) {
            Map.Entry<?, ?> entry = (Map.Entry<?, ?>)ent;
            nspref.put((String)entry.getValue(), (String)entry.getKey());
        }
        JAXBUtils.setNamespaceMapper(nspref, u);
        u.marshal(mObj, writer);
        writer.flush();
    } catch (Exception ex) {
        throw new WSDLException(WSDLException.PARSER_ERROR,
                                "",
                                ex);
    }

}
 
Example 20
Source File: StaxStreamWriter.java    From sis with Apache License 2.0 3 votes vote down vote up
/**
 * Delegates to JAXB the marshalling of a part of XML document.
 * The XML content will be written in an element of the given name with no namespace (see below).
 *
 * <h4>Hiding namespace</h4>
 * The {@code hideNS} argument, if non-null, gives a namespace to remove in the marshalling result.
 * There is two reasons why we may want to hide a namespace. The most straightforward reason is to
 * simplify the XML document when the {@linkplain javax.xml.bind.annotation.XmlElement#namespace()
 * namespace of elements} to marshal is the {@linkplain XMLStreamWriter#setDefaultNamespace(String)
 * default namespace}. Since some JAXB implementation systematically inserts a prefix no matter if
 * the namespace is the default one or not, we have to manually erase the namespace when it is the
 * default one.
 *
 * <p>But a more convolved reason is to reuse an element defined for another version of the file format.
 * For example some elements may be identical in 1.0 and 1.1 versions of a file format, so we may want
 * to define only one JAXB annotated class for both versions. In that case the {@code hideNS} argument is
 * <strong>not</strong> necessarily the {@linkplain XMLStreamWriter#setDefaultNamespace(String) default namespace}.
 * It is rather the namespace of the JAXB element that we want to erase (for example {@code "foo/1.1"}),
 * in order to pretend that it is the element of a different version specified by the default namespace
 * (for example defined by {@code xmlns = "foo/1.0"}).</p>
 *
 * @param  <T>     compile-time value of the {@code type} argument.
 * @param  hideNS  the namespace to erase from the marshalling output, or {@code null} if none.
 * @param  name    the XML tag to write.
 * @param  type    the Java class that define the XML schema of the object to marshal.
 * @param  object  the object to marshal, or {@code null} if none.
 * @throws XMLStreamException if the XML stream is closed.
 * @throws JAXBException if an error occurred during marshalling.
 *
 * @see javax.xml.bind.Marshaller#marshal(Object, XMLStreamWriter)
 */
protected final <T> void marshal(final String hideNS, final String name, final Class<T> type, final T object)
        throws XMLStreamException, JAXBException
{
    Marshaller m = marshaller;
    if (m == null) {
        m = getMarshallerPool().acquireMarshaller();
        m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);     // Formatting will be done by FormattedWriter.
        final Charset encoding = owner.encoding;
        if (encoding != null) {
            m.setProperty(Marshaller.JAXB_ENCODING, encoding.name());
        }
        for (final Map.Entry<String,?> entry : ((Map<String,?>) owner.configuration).entrySet()) {
            m.setProperty(entry.getKey(), entry.getValue());
        }
    }
    final QName qn;
    XMLStreamWriter out = writer;
    if (hideNS != null) {
        out = new NamespaceEraser(out, hideNS);
        qn  = new QName(hideNS, name);
    } else {
        qn  = new QName(name);
    }
    marshaller = null;
    m.marshal(new JAXBElement<>(qn, type, object), out);
    marshaller = m;                                                   // Allow reuse or recycling only on success.
}