示例#1
1
  /**
   * Serialize object to XML and output it to given OutputStream
   *
   * @param object objec to marshal
   * @param outputStream stream to put the resulting XML to
   */
  public void marshal(Object object, OutputStream outputStream) {
    try {
      XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
      outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
      ByteArrayOutputStream tempOutput = null;
      XMLStreamWriter writer = null;

      if (autoIndent) {
        tempOutput = new ByteArrayOutputStream();
        writer = outputFactory.createXMLStreamWriter(tempOutput);
      } else {
        writer = outputFactory.createXMLStreamWriter(outputStream);
      }

      //            if (autoIndent) {
      //                writer = new IndentingXMLStreamWriterDecorator(writer);
      //            }

      writerContext.writer = writer;

      writer.writeStartDocument();

      marshalObject(writer, object);

      writer.writeEndDocument();
      writer.close();

      if (autoIndent) {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty("doctype-public", "yes");
        transformer.transform(
            new StreamSource(new ByteArrayInputStream(tempOutput.toByteArray())),
            new StreamResult(outputStream));
      }

    } catch (TransformerException ex) {
      throw new XmlizerException("Error whule indenting XML", ex);
    } catch (XMLStreamException ex) {
      throw new XmlizerException("Error occured while writting", ex);
    } catch (IllegalAccessException ex) {
      throw new XmlizerException("Error while trying to read a property", ex);
    } catch (IllegalArgumentException ex) {
      throw new XmlizerException("Error while trying to read a property", ex);
    } catch (InvocationTargetException ex) {
      throw new XmlizerException("Error while trying to read a property", ex);
    }
  }