Java 类javax.xml.transform.OutputKeys 实例源码

项目:Random-Music-Generator    文件:XMLGenerator.java   
private void saveDocumentTo() throws XMLException {
    try {
        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer transf = tfactory.newTransformer();

        transf.setOutputProperty( OutputKeys.INDENT, "yes" );
        transf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transf.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "no" );
        transf.setOutputProperty( OutputKeys.METHOD, "xml" );

        DOMImplementation impl = doc.getImplementation();
        DocumentType doctype = impl.createDocumentType( "doctype", 
                "-//Recordare//DTD MusicXML 3.0 Partwise//EN", "http://www.musicxml.org/dtds/partwise.dtd" );

        transf.setOutputProperty( OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId() );
        transf.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId() );

        DOMSource src = new DOMSource( doc );
        StreamResult resultS = new StreamResult( file );
        transf.transform( src, resultS );

    } catch ( TransformerException e ) {
        throw new XMLException( "Could not save the File" );
    }
}
项目:GmArchMvvm    文件:CharacterHandler.java   
/**
 * xml format
 *
 * @param xml The xml string to be formatted
 * @return formatted after the new string
 */
public static String xmlFormat(String xml) {
    if (TextUtils.isEmpty(xml)) {
        return "Empty/Null xml content";
    }
    String message;
    try {
        Source xmlInput = new StreamSource(new StringReader(xml));
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(xmlInput, xmlOutput);
        message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
    } catch (TransformerException e) {
        message = xml;
    }
    return message;
}
项目:solr-upgrade-tool    文件:ConfigTransformer.java   
protected Transformer buildTransformer(ToolParams params, ProcessorConfig procConfig)
    throws TransformerConfigurationException {
  Transformer result = params.getFactory().newTransformer(); // identity transform.

  if (procConfig.getTransformerPath() != null) {
    Path scriptPath = Paths.get(procConfig.getTransformerPath());
    if (!scriptPath.isAbsolute()) {
      scriptPath = params.getProcessorConfPath().getParent().resolve(scriptPath);
    }
    if (!Files.exists(scriptPath)) {
      throw new IllegalArgumentException("Unable to find transformation script "+scriptPath);
    }
    result = params.getFactory().newTransformer(new StreamSource(scriptPath.toFile()));
  }

  result.setOutputProperty(OutputKeys.INDENT, "yes");
  result.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
  return result;
}
项目:freecol    文件:Utils.java   
/**
 * Helper to make an XML Transformer.
 *
 * @param declaration If true, include the XML declaration.
 * @param indent If true, set up the transformer to indent.
 * @return A suitable {@code Transformer}.
 */
public static Transformer makeTransformer(boolean declaration,
                                          boolean indent) {
    Transformer tf = null;
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        factory.setAttribute("indent-number", new Integer(2));
        tf = factory.newTransformer();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tf.setOutputProperty(OutputKeys.METHOD, "xml");
        if (!declaration) {
            tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
        if (indent) {
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }
    } catch (TransformerException e) {
        logger.log(Level.WARNING, "Failed to install transformer!", e);
    }
    return tf;
}
项目:litiengine    文件:XmlUtilities.java   
/**
 * Saves the xml, contained by the specified input with the custom indentation.
 * If the input is the result of jaxb marshalling, make sure to set
 * Marshaller.JAXB_FORMATTED_OUTPUT to false in order for this method to work
 * properly.
 * 
 * @param input
 * @param fos
 * @param indentation
 */
public static void saveWithCustomIndetation(ByteArrayInputStream input, FileOutputStream fos, int indentation) {
  try {
    Transformer transformer = SAXTransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indentation));
    Source xmlSource = new SAXSource(new org.xml.sax.InputSource(input));
    StreamResult res = new StreamResult(fos);
    transformer.transform(xmlSource, res);
    fos.flush();
    fos.close();
  } catch (TransformerFactoryConfigurationError | TransformerException | IOException e) {
    log.log(Level.SEVERE, e.getMessage(), e);
  }
}
项目:incubator-netbeans    文件:XMLUtil.java   
public static void write(Document doc, OutputStream out) throws IOException {
    // XXX note that this may fail to write out namespaces correctly if the document
    // is created with namespaces and no explicit prefixes; however no code in
    // this package is likely to be doing so
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer(
                new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        DocumentType dt = doc.getDoctype();
        if (dt != null) {
            String pub = dt.getPublicId();
            if (pub != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub);
            }
            t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dt.getSystemId());
        }
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N
        Source source = new DOMSource(doc);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (Exception | TransformerFactoryConfigurationError e) {
        throw new IOException(e);
    }
}
项目:pay    文件:XmlUtils.java   
/**
 * Converts the Node/Document/Element instance to XML payload.
 *
 * @param node the node/document/element instance to convert
 * @return the XML payload representing the node/document/element
 * @throws AlipayApiException problem converting XML to string
 */
public static String nodeToString(Node node) throws AlipayApiException {
    String payload = null;

    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();

        Properties props = tf.getOutputProperties();
        props.setProperty(OutputKeys.INDENT, LOGIC_YES);
        props.setProperty(OutputKeys.ENCODING, DEFAULT_ENCODE);
        tf.setOutputProperties(props);

        StringWriter writer = new StringWriter();
        tf.transform(new DOMSource(node), new StreamResult(writer));
        payload = writer.toString();
        payload = payload.replaceAll(REG_INVALID_CHARS, " ");
    } catch (TransformerException e) {
        throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
    }

    return payload;
}
项目:stvs    文件:XmlExporter.java   
/**
 * Exports an Object as xml.
 *
 * @param source Object to export
 * @return The output xml is written to this stream
 * @throws ExportException Exception while exporting
 */
public ByteArrayOutputStream export(F source) throws ExportException {
    Node xmlNode = exportToXmlNode(source);
    StringWriter writer = new StringWriter();
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(xmlNode), new StreamResult(writer));
        String xmlString = writer.toString();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        stream.write(xmlString.getBytes("utf-8"));
        return stream;
    } catch (TransformerException | IOException e) {
        throw new ExportException(e);
    }
}
项目:Equella    文件:RequestParameter.java   
private static String element2String(Element element)
{
    StringWriter result = new StringWriter();

    DOMSource source = new DOMSource(element);
    StreamResult destination = new StreamResult(result);

    TransformerFactory factory = TransformerFactory.newInstance();
    try
    {
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(source, destination);
    }
    catch( TransformerException ex )
    {
        throw new RuntimeException("Error transforming element to xml string", ex);
    }

    return result.toString();
}
项目:OperatieBRP    文件:AbstractDienstVerzoekParser.java   
/**
 * Hulpmethode om een xml fragment uit een node te halen middels xpath.
 * @param locatie de locatie van de node als xpath.
 * @param xPath een XPath instantie
 * @param node de basis node
 * @return de text
 */
protected static String getXmlFragment(final String locatie, final XPath xPath, final Node node) {
    try {
        final Node xPathNode = (Node) xPath.evaluate(locatie, node, XPathConstants.NODE);
        if (xPathNode != null) {
            final StringWriter buf = new StringWriter();
            final Transformer xform = TransformerFactory.newInstance().newTransformer();
            xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            xform.transform(new DOMSource(xPathNode), new StreamResult(buf));
            return buf.toString();
        }
    } catch (final XPathExpressionException | TransformerException e) {
        LOGGER.error("XPath voor text content kon niet worden geëvalueerd voor locatie {}.", locatie);
        throw new UnsupportedOperationException(e);
    }
    return null;
}
项目:cuttlefish    文件:GraphMLExporter.java   
public void export(File file) {
    try {
        // Create the GraphML Document
        docFactory = DocumentBuilderFactory.newInstance();
        docBuilder = docFactory.newDocumentBuilder();
        doc = docBuilder.newDocument();

        // Export the data
        exportData();

        // Save data as GraphML file
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(file);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(source, result);

    } catch (TransformerException te) {
        te.printStackTrace();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    }
}
项目:Aurora    文件:CharacterHandler.java   
/**
 * xml 格式化
 *
 * @param xml
 * @return
 */
public static String xmlFormat(String xml) {
    if (TextUtils.isEmpty(xml)) {
        return "Empty/Null xml content";
    }
    String message;
    try {
        Source xmlInput = new StreamSource(new StringReader(xml));
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(xmlInput, xmlOutput);
        message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
    } catch (TransformerException e) {
        message = xml;
    }
    return message;
}
项目:KeYExperienceReport    文件:ResultToSPL.java   
private static void writeOut(Document doc, File f)
        throws TransformerException {
    TransformerFactory transformerFactory = TransformerFactory
            .newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
    DOMSource source = new DOMSource(doc);
    f.delete();
    StreamResult result = new StreamResult(f);

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);

    System.out.println("File saved!");

}
项目:KeYExperienceReport    文件:FeatureIdeOpltionGenerator.java   
private static void writeOut(Document doc) throws TransformerException {
    TransformerFactory transformerFactory = TransformerFactory
            .newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
    DOMSource source = new DOMSource(doc);
    File f = new File("file.xml");
    f.delete();
    StreamResult result = new StreamResult(f);

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);

    System.out.println("File saved!");

}
项目:KeYExperienceReport    文件:SPL2OpltionGenerator.java   
private static void writeOut(Document doc) throws TransformerException {
    TransformerFactory transformerFactory = TransformerFactory
            .newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
    DOMSource source = new DOMSource(doc);
    File f = new File("splFile.xml");
    f.delete();
    StreamResult result = new StreamResult(f);

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);

    System.out.println("File saved!");

}
项目:19porn    文件:LogFormat.java   
public static String formatXml(String xml) {
    String formatted = null;
    if (xml == null || xml.trim().length() == 0) {
        return formatted;
    }
    try {
        Source xmlInput = new StreamSource(new StringReader(xml));
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                String.valueOf(XML_INDENT));
        transformer.transform(xmlInput, xmlOutput);
        formatted = xmlOutput.getWriter().toString().replaceFirst(">", ">"
                + XPrinter.lineSeparator);
    } catch (Exception e) {

    }
    return formatted;
}
项目:VASSAL-src    文件:Builder.java   
/**
 * Write an XML document to a Writer
 */
public static void writeDocument(Document doc, Writer writer)
                                                        throws IOException {
  final Source source = new DOMSource(doc);

  // Prepare the output file
  final Result result = new StreamResult(writer);

  // Write the DOM document to the file
  try {
    final Transformer xformer =
      TransformerFactory.newInstance().newTransformer();
    xformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
    xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
    xformer.transform(source, result);
  }
  catch (TransformerException e) {
    // FIXME: switch to IOException(Throwable) ctor in Java 1.6
    throw (IOException) new IOException().initCause(e);
  }
}
项目:fluentxml4j    文件:FluentXmlTransformerIntegrationTest.java   
@Test
public void streamToStringWithTransformers() throws Exception
{
    String resultXml = fluentXmlTransformer
            .transform(sourceDocumentRule.asInputStream())
            .withStylesheet(xsltDocumentRule.asDocument())
            .withStylesheet(xsltDocumentRule2.asInputStream())
            .withStylesheet(xsltDocumentRule3.asUrl())
            .withSerializer(new SerializerConfigurerAdapter()
            {
                @Override
                protected void configure(Transformer transformer)
                {
                    super.configure(transformer);
                    transformer.setOutputProperty(OutputKeys.INDENT, "no");
                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                }
            })
            .toString();

    assertThat(resultXml, is("<transformed3/>"));
}
项目:fluentxml4j    文件:FluentXmlTransformerIntegrationTest.java   
@Test
public void streamToBytesWithTransformers() throws Exception
{
    byte[] bytes = fluentXmlTransformer
            .transform(sourceDocumentRule.asInputStream())
            .withStylesheet(xsltDocumentRule.asDocument())
            .withStylesheet(xsltDocumentRule2.asInputStream())
            .withStylesheet(xsltDocumentRule3.asUrl())
            .withSerializer(new SerializerConfigurerAdapter()
            {
                @Override
                protected void configure(Transformer transformer)
                {
                    super.configure(transformer);
                    transformer.setOutputProperty(OutputKeys.INDENT, "no");
                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                }
            })
            .toBytes();

    assertThat(new String(bytes, "UTF-8"), is("<transformed3/>"));
}
项目:fluentxml4j    文件:FluentXmlTransformerIntegrationTest.java   
@Test
public void documentWithPrefixMappingToString() throws Exception
{
    String xml = fluentXmlTransformer
            .transform(sourceDocumentWithNSRule.asDocument())
            .withPrefixMapping("ns1", "ns2")
            .withSerializer(new SerializerConfigurerAdapter()
            {
                @Override
                protected void configure(Transformer transformer)
                {
                    super.configure(transformer);
                    transformer.setOutputProperty(OutputKeys.INDENT, "no");
                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                }
            })
            .toString();

    assertThat(xml, is("<ns2:source xmlns:ns2=\"uri:ns\" xmlns=\"uri:ns\" xmlns:ns1=\"uri:ns\"/>"));
}
项目:fluentxml4j    文件:FluentXmlTransformerIntegrationTest.java   
@Test
public void documentWithPrefixMappingToDefaultToString() throws Exception
{
    String xml = fluentXmlTransformer
            .transform(sourceDocumentWithNSRule.asDocument())
            .withPrefixMapping("ns1", "")
            .withSerializer(new SerializerConfigurerAdapter()
            {
                @Override
                protected void configure(Transformer transformer)
                {
                    super.configure(transformer);
                    transformer.setOutputProperty(OutputKeys.INDENT, "no");
                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                }
            })
            .toString();

    assertThat(xml, is("<source xmlns=\"uri:ns\" xmlns:ns1=\"uri:ns\" xmlns:ns2=\"uri:ns\"/>"));
}
项目:fluentxml4j    文件:FluentXmlTransformerIntegrationTest.java   
@Test
public void documentWithPrefixMappingFromDefaultToString() throws Exception
{
    String xml = fluentXmlTransformer
            .transform(sourceDocumentWithDefaultNSRule.asDocument())
            .withPrefixMapping("", "ns1")
            .withSerializer(new SerializerConfigurerAdapter()
            {
                @Override
                protected void configure(Transformer transformer)
                {
                    super.configure(transformer);
                    transformer.setOutputProperty(OutputKeys.INDENT, "no");
                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                }
            })
            .toString();

    assertThat(xml, is("<ns1:source xmlns:ns1=\"uri:ns\" xmlns=\"uri:ns\"/>"));
}
项目:fluentxml4j    文件:FluentXmlTransformerIntegrationTest.java   
@Test
public void transformWithJAXBAndStylesheetToString() throws Exception
{
    String xml = fluentXmlTransformer.transform(JAXBContext.newInstance(JaxbSource.class), new JaxbSource())
            .withStylesheet(this.xsltDocumentRule.asDocument())
            .withSerializer(new SerializerConfigurerAdapter()
            {
                @Override
                protected void configure(Transformer transformer)
                {
                    super.configure(transformer);
                    transformer.setOutputProperty(OutputKeys.INDENT, "no");
                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                }
            })
            .toString();

    assertThat(xml, is("<transformed1/>"));
}
项目:javaide    文件:MergerXmlUtils.java   
/**
 * Outputs the given XML {@link Document} to the file {@code outFile}.
 *
 * TODO right now reformats the document. Needs to output as-is, respecting white-space.
 *
 * @param doc The document to output. Must not be null.
 * @param outFile The {@link File} where to write the document.
 * @param log A log in case of error.
 * @return True if the file was written, false in case of error.
 */
static boolean printXmlFile(
        @NonNull Document doc,
        @NonNull File outFile,
        @NonNull IMergerLog log) {
    // Quick thing based on comments from http://stackoverflow.com/questions/139076
    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");         //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");                   //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.INDENT, "yes");                       //$NON-NLS-1$
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",     //$NON-NLS-1$
                             "4");                                            //$NON-NLS-1$
        tf.transform(new DOMSource(doc), new StreamResult(outFile));
        return true;
    } catch (TransformerException e) {
        log.error(Severity.ERROR,
                new FileAndLine(outFile.getName(), 0),
                "Failed to write XML file: %1$s",
                e.toString());
        return false;
    }
}
项目:Tarski    文件:GraphBuilder.java   
/**
 * Writes given xmlDocument to xml file.
 *
 * @param xmlDocument
 */
@SuppressWarnings("unused")
private void writeXml(final Document xmlDocument) {
  Transformer transformer;
  try {
    transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
    final DOMSource source = new DOMSource(xmlDocument);
    // final StreamResult console =
    // new StreamResult(new File("C:/Users/emre.kirmizi/Desktop/out.xml"));
    final StreamResult console =
        new StreamResult(new File("C:/Users/anil.ozturk/Desktop/out.xml"));
    transformer.transform(source, console);
  } catch (TransformerFactoryConfigurationError | TransformerException e) {
    e.printStackTrace();
  }
}
项目:fluentxml4j    文件:FluentXmlSerializerIntegrationTest.java   
@Test
public void serializeWithJAXBToString() throws Exception
{
    String serializedXml = serialize(JAXBContext.newInstance(JaxbRoot.class), new JaxbRoot())
            .withSerializer(new SerializerConfigurerAdapter()
            {
                @Override
                protected void configure(Transformer transformer)
                {
                    super.configure(transformer);
                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                    transformer.setOutputProperty(OutputKeys.INDENT, "no");
                }
            })
        .toString();

    assertThat(serializedXml, is("<ns:jaxb-root xmlns:ns=\"uri:ns1\" xmlns=\"uri:ns1\"/>"));
}
项目:alfresco-repository    文件:SchemaToXML.java   
public SchemaToXML(Schema schema, StreamResult streamResult)
{
    final SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance();
    try
    {
        xmlOut = stf.newTransformerHandler();
    }
    catch (TransformerConfigurationException error)
    {
        throw new RuntimeException("Unable to create TransformerHandler.", error);
    }
    final Transformer t = xmlOut.getTransformer();
    try
    {
        t.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2");
    }
    catch (final IllegalArgumentException e)
    {
        // It was worth a try
    }
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty(OutputKeys.ENCODING, SchemaComparator.CHAR_SET);
    xmlOut.setResult(streamResult);

    this.schema = schema;
}
项目:coteafs-services    文件:XmlPayloadLogger.java   
@Override
public String [] getPayload (final PayloadType type, final String body) {
    final Source input = new StreamSource (new StringReader (body));
    final StringWriter writer = new StringWriter ();
    final StreamResult output = new StreamResult (writer);
    final TransformerFactory transformerFactory = TransformerFactory.newInstance ();
    transformerFactory.setAttribute ("indent-number", 4);
    try {
        final Transformer transformer = transformerFactory.newTransformer ();
        transformer.setOutputProperty (OutputKeys.INDENT, "yes");
        transformer.transform (input, output);
        return output.getWriter ()
            .toString ()
            .split ("\n");
    }
    catch (final TransformerException e) {
        fail (XmlFormatTransformerError.class, "Error while Xml Transformation.", e);
    }
    return new String [] {};
}
项目:jaer    文件:TaFileStorage.java   
public void release() {
    try {
        if( isWrite == false) {
            System.err.println("Try release of file with no write flags");
            return;
        }

        DOMSource source = new DOMSource(doc);

        StreamResult result = new StreamResult(file);

        // write to xml file
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // do it
        transformer.transform(source, result);
    } catch(Exception e) {
        e.printStackTrace();
    }
}
项目:neoscada    文件:XMLBase.java   
protected void storeXmlDocument ( final Document doc, final File file ) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException
{
    // create output directory

    file.getParentFile ().mkdirs ();

    // write out xml

    final TransformerFactory transformerFactory = TransformerFactory.newInstance ();

    final Transformer transformer = transformerFactory.newTransformer ();
    transformer.setOutputProperty ( OutputKeys.INDENT, "yes" ); //$NON-NLS-1$

    final DOMSource source = new DOMSource ( doc );
    final StreamResult result = new StreamResult ( file );
    transformer.transform ( source, result );
}
项目:BaseClient    文件:ParticleIO.java   
/**
 * Save a single emitter to the XML file
 * 
 * @param out
 *            The location to which we should save
 * @param emitter
 *            The emitter to store to the XML file
 * @throws IOException
 *             Indicates a failure to write or encode the XML
 */
public static void saveEmitter(OutputStream out, ConfigurableEmitter emitter)
        throws IOException {
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document document = builder.newDocument();

        document.appendChild(emitterToElement(document, emitter));
        Result result = new StreamResult(new OutputStreamWriter(out,
                "utf-8"));
        DOMSource source = new DOMSource(document);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer xformer = factory.newTransformer();
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");

        xformer.transform(source, result);
    } catch (Exception e) {
        Log.error(e);
        throw new IOException("Failed to save emitter");
    }
}
项目:javaide    文件:MergerXmlUtils.java   
/**
 * Outputs the given XML {@link Document} as a string.
 *
 * TODO right now reformats the document. Needs to output as-is, respecting white-space.
 *
 * @param doc The document to output. Must not be null.
 * @param log A log in case of error.
 * @return A string representation of the XML. Null in case of error.
 */
static String printXmlString(
        @NonNull Document doc,
        @NonNull IMergerLog log) {
    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");        //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");                  //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.INDENT, "yes");                      //$NON-NLS-1$
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",    //$NON-NLS-1$
                             "4");                                           //$NON-NLS-1$
        StringWriter sw = new StringWriter();
        tf.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException e) {
        log.error(Severity.ERROR,
                new FileAndLine(extractXmlFilename(doc), 0),
                "Failed to write XML file: %1$s",
                e.toString());
        return null;
    }
}
项目:NeiHanDuanZiTV    文件:CharacterHandler.java   
/**
 * xml 格式化
 *
 * @param xml
 * @return
 */
public static String xmlFormat(String xml) {
    if (TextUtils.isEmpty(xml)) {
        return "Empty/Null xml content";
    }
    String message;
    try {
        Source xmlInput = new StreamSource(new StringReader(xml));
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(xmlInput, xmlOutput);
        message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
    } catch (TransformerException e) {
        message = xml;
    }
    return message;
}
项目:DAFramework    文件:DomXmlUtils.java   
/**
 * 获取一个Transformer对象,由于使用时都做相同的初始化,所以提取出来作为公共方法。
 *
 * @return a Transformer encoding gb2312
 */

public static Transformer newTransformer() {
    try {
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer();
        Properties properties = transformer.getOutputProperties();
        properties.setProperty(OutputKeys.ENCODING, "gb2312");
        properties.setProperty(OutputKeys.METHOD, "xml");
        properties.setProperty(OutputKeys.VERSION, "1.0");
        properties.setProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperties(properties);
        return transformer;
    } catch (TransformerConfigurationException tce) {
        throw new RuntimeException(tce.getMessage());
    }
}
项目:bohemia    文件:XmlUtils.java   
/** 
 * Converts the Node/Element instance to XML payload. 
 * 
 * @param node the node/element instance to convert 
 * @return the XML payload representing the node/element 
 * @throws XmlException problem converting XML to string 
 */  
public static String childNodeToString(Node node) throws XmlException {  
    String payload = null;  

    try {  
        Transformer tf = TransformerFactory.newInstance().newTransformer();  

        Properties props = tf.getOutputProperties();  
        props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);  
        tf.setOutputProperties(props);  

        StringWriter writer = new StringWriter();  
        tf.transform(new DOMSource(node), new StreamResult(writer));  
        payload = writer.toString();  
        payload = payload.replaceAll(REG_INVALID_CHARS, " ");  
    } catch (TransformerException e) {  
        throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e);  
    }  

    return payload;  
}
项目:bohemia    文件:XmlUtils.java   
/** 
 * Converts the Node/Document/Element instance to XML payload. 
 * 
 * @param node the node/document/element instance to convert 
 * @return the XML payload representing the node/document/element 
 * @throws XmlException problem converting XML to string 
 */  
public static String nodeToString(Node node) throws XmlException {  
    String payload = null;  

    try {  
        Transformer tf = TransformerFactory.newInstance().newTransformer();  

        Properties props = tf.getOutputProperties();  
        props.setProperty(OutputKeys.INDENT, LOGIC_YES);  
        props.setProperty(OutputKeys.ENCODING, DEFAULT_ENCODE);  
        tf.setOutputProperties(props);  

        StringWriter writer = new StringWriter();  
        tf.transform(new DOMSource(node), new StreamResult(writer));  
        payload = writer.toString();  
        payload = payload.replaceAll(REG_INVALID_CHARS, " ");  
    } catch (TransformerException e) {  
        throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e);  
    }  

    return payload;  
}
项目:bohemia    文件:XmlUtils.java   
/** 
 * Transforms the XML content to XHTML/HTML format string with the XSL. 
 * 
 * @param payload the XML payload to convert 
 * @param xsltFile the XML stylesheet file 
 * @return the transformed XHTML/HTML format string 
 * @throws XmlException problem converting XML to HTML 
 */  
public static String xmlToHtml(String payload, File xsltFile)  
        throws XmlException {  
    String result = null;  

    try {  
        Source template = new StreamSource(xsltFile);  
        Transformer transformer = TransformerFactory.newInstance()  
                .newTransformer(template);  

        Properties props = transformer.getOutputProperties();  
        props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);  
        transformer.setOutputProperties(props);  

        StreamSource source = new StreamSource(new StringReader(payload));  
        StreamResult sr = new StreamResult(new StringWriter());  
        transformer.transform(source, sr);  

        result = sr.getWriter().toString();  
    } catch (TransformerException e) {  
        throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e);  
    }  

    return result;  
}
项目:Logg    文件:XmlPrinter.java   
@Override
public void printer(Type type, String tag, String object) {
    String xml;
    try {
        Source xmlInput = new StreamSource(new StringReader(object));
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(xmlInput, xmlOutput);
        xml = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
    } catch (TransformerException e) {
        xml = object;
    }
    super.printer(type, tag, xml);
}
项目:pay    文件:XmlUtils.java   
/**
 * Converts the Node/Element instance to XML payload.
 *
 * @param node the node/element instance to convert
 * @return the XML payload representing the node/element
 * @throws AlipayApiException problem converting XML to string
 */
public static String childNodeToString(Node node) throws AlipayApiException {
    String payload = null;

    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();

        Properties props = tf.getOutputProperties();
        props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
        tf.setOutputProperties(props);

        StringWriter writer = new StringWriter();
        tf.transform(new DOMSource(node), new StreamResult(writer));
        payload = writer.toString();
        payload = payload.replaceAll(REG_INVALID_CHARS, " ");
    } catch (TransformerException e) {
        throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
    }

    return payload;
}
项目:oscm    文件:XmlDocument.java   
/**
 * Converts the given document to an XML string. Uses UTF-8 as character
 * encoding.
 * 
 * @return the XML as byte array
 */
byte[] docToXml() {
    try {
        DOMSource domSource = new DOMSource(xmldoc);
        final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(buffer);
        Transformer transformer = Transformers.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(
                "{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(domSource, result);
        return buffer.toByteArray();
    } catch (TransformerException e) {
        throw new SaaSSystemException(e);
    }
}