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

项目: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" );
    }
}
项目:Equella    文件:XsltServiceImpl.java   
/**
 * Performs the XSLT transformation.
 */
private String doTransform(final Transformer transformer, final Source input, final URIResolver resolver)
{
    final StringWriter writer = new StringWriter();
    final StreamResult output = new StreamResult(writer);

    if( resolver != null )
    {
        transformer.setURIResolver(resolver);
    }

    try
    {
        transformer.transform(input, output);
    }
    catch( final TransformerException ex )
    {
        throw new RuntimeException("Error transforming XSLT", ex);
    }

    return writer.toString();
}
项目:openjdk-jdk10    文件:Bug6490921.java   
@Test
public void test02() {
    String xml = "<?xml version='1.0'?><root/>";
    ReaderStub.used = false;
    setSystemProperty("org.xml.sax.driver", ReaderStub.class.getName());
    try {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        InputSource in = new InputSource(new StringReader(xml));
        SAXSource source = new SAXSource(in);
        StreamResult result = new StreamResult(new StringWriter());
        transformer.transform(source, result);
        Assert.assertTrue(printWasReaderStubCreated());
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
}
项目: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();
    }
}
项目:jdk8u-jdk    文件:Test.java   
private static String toString(Source response) throws TransformerException, IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(response, new StreamResult(bos));
    bos.close();
    return new String(bos.toByteArray());
}
项目: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;
    }
}
项目:openjdk-jdk10    文件:URIResolverTest.java   
/**
 * This is to test the URIResolver.resolve() method when there is an error
 * in the file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public static void docResolver01() throws Exception {
    try (FileInputStream fis = new FileInputStream(XML_DIR + "doctest.xsl")) {
        URIResolverTest resolver = new URIResolverTest("temp/colors.xml", SYSTEM_ID);
        StreamSource streamSource = new StreamSource(fis);
        streamSource.setSystemId(SYSTEM_ID);

        Transformer transformer = TransformerFactory.newInstance().newTransformer(streamSource);
        transformer.setURIResolver(resolver);

        File f = new File(XML_DIR + "myFake.xml");
        Document document = DocumentBuilderFactory.newInstance().
                newDocumentBuilder().parse(f);

        // Use a Transformer for output
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(System.err);
        // No exception is expected because resolver resolve wrong URI.
        transformer.transform(source, result);
    }
}
项目:openjdk-jdk10    文件:MexEntityResolver.java   
public MexEntityResolver(List<? extends Source> wsdls) throws IOException {
    Transformer transformer = XmlUtil.newTransformer();
    for (Source source : wsdls) {
        XMLStreamBufferResult xsbr = new XMLStreamBufferResult();
        try {
            transformer.transform(source, xsbr);
        } catch (TransformerException e) {
            throw new WebServiceException(e);
        }
        String systemId = source.getSystemId();

        //TODO: can we do anything if the given mex Source has no systemId?
        if(systemId != null){
            SDDocumentSource doc = SDDocumentSource.create(JAXWSUtils.getFileOrURL(systemId), xsbr.getXMLStreamBuffer());
            this.wsdls.put(systemId, doc);
        }
    }
}
项目:oscm    文件:XMLConverter.java   
public static String convertToString(Source source,
        boolean includeXmlDeclaration) throws TransformerException {

    Transformer transformer = Transformers.newFormatingTransformer();
    if (!includeXmlDeclaration) {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                "yes");
    }

    StringWriter stringWriter = new StringWriter();
    try {
        transformer.transform(source, new StreamResult(stringWriter));
        return stringWriter.toString();
    } finally {
        try {
            stringWriter.close();
        } catch (IOException e) {
            // ignore
        }
    }
}
项目:pgcodekeeper    文件:XmlStringList.java   
public <T> void serializeList(List<T> listToConvert, boolean noFormatting,
        Writer writer) throws TransformerException, IOException {
    Document xml;
    try {
        xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException ex) {
        throw new IOException(ex);
    }

    Element root = xml.createElement(rootTagName);
    xml.appendChild(root);

    for (T listElement : listToConvert) {
        Element newElement = xml.createElement(elementTagName);
        newElement.setTextContent(listElement.toString());
        root.appendChild(newElement);
    }

    Transformer tf =  TransformerFactory.newInstance().newTransformer();
    if (!noFormatting) {
        tf.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    tf.transform(new DOMSource(xml), new StreamResult(writer));
}
项目:featurea    文件:XMLOutputVisitor.java   
private void doTransform(String sXSL, OutputStream os) throws javax.xml.transform.TransformerConfigurationException, javax.xml.transform.TransformerException {
    // create the transformerfactory & transformer instance
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();

    if (null == sXSL) {
        t.transform(new DOMSource(doc), new StreamResult(os));
        return;
    }

    try {
        Transformer finalTransformer = tf.newTransformer(new StreamSource(sXSL));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        t.transform(new DOMSource(doc), new StreamResult(bos));
        bos.flush();
        StreamSource xmlSource = new StreamSource(new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray())));
        finalTransformer.transform(xmlSource, new StreamResult(os));
    } catch (IOException ioe) {
        throw new javax.xml.transform.TransformerException(ioe);
    }
}
项目:OSWf-OSWorkflow-fork    文件:WfDefinitionServiceImpl.java   
String colorizeXML(String xml, String xsltFilename) throws TransformerConfigurationException, TransformerException {

       // Get the XSLT file as a resource
       InputStream xslt = getClass().getResourceAsStream(xsltFilename);

       // Create and configure XSLT Transformer 
       TransformerFactory factory = TransformerFactory.newInstance();
       Transformer transformer = factory.newTransformer(new StreamSource(xslt));
       transformer.setParameter("indent-elements", "yes");

       OutputStream outputStream = new ByteArrayOutputStream();
       InputStream inputStream = new ByteArrayInputStream(xml.getBytes());

       // Convert the XML into HTML per the XSLT file
       transformer.transform(new StreamSource(inputStream), new StreamResult(outputStream));

       return new String(((ByteArrayOutputStream)outputStream).toByteArray());
   }
项目:openjdk-jdk10    文件:SAX2DOMTest.java   
@Test
public void test() throws Exception {
    SAXParserFactory fac = SAXParserFactory.newInstance();
    fac.setNamespaceAware(true);
    SAXParser saxParser = fac.newSAXParser();

    StreamSource sr = new StreamSource(this.getClass().getResourceAsStream("SAX2DOMTest.xml"));
    InputSource is = SAXSource.sourceToInputSource(sr);
    RejectDoctypeSaxFilter rf = new RejectDoctypeSaxFilter(saxParser);
    SAXSource src = new SAXSource(rf, is);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    DOMResult result = new DOMResult();
    transformer.transform(src, result);

    Document doc = (Document) result.getNode();
    System.out.println("Name" + doc.getDocumentElement().getLocalName());

    String id = "XWSSGID-11605791027261938254268";
    Element selement = doc.getElementById(id);
    if (selement == null) {
        System.out.println("getElementById returned null");
    }

}
项目:knime-json-node-doc-generator    文件:XmlUtils.java   
/**
 * Strips namespace information form the given node, to ease further processing.
 * I took the XSLT transformation from <a href=
 * "http://clardeur.blogspot.de/2012/11/remove-all-namespaces-from-xml-using.html">here</a>.
 * 
 * @param node
 *            The node.
 * @return A transformed node without namespace info.
 */
public static Node removeNamespaces(Node node) {
    Objects.requireNonNull(node, "node must not be null");
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    InputStream xslt = XmlUtils.class.getResourceAsStream(REMOVE_NAMESPACE_XSLT);
    if (xslt == null) {
        throw new IllegalStateException("Could not load " + REMOVE_NAMESPACE_XSLT + " -- InputStream == null");
    }
    DOMResult result = new DOMResult();
    try {
        Transformer transformer = transformerFactory.newTransformer(new StreamSource(xslt));
        transformer.transform(new DOMSource(node), result);
    } catch (TransformerException e) {
        throw new IllegalStateException(e);
    }
    return result.getNode();
}
项目:ProyectoPacientes    文件:JDBC4MysqlSQLXML.java   
protected String domSourceToString() throws SQLException {
    try {
        DOMSource source = new DOMSource(this.asDOMResult.getNode());
        Transformer identity = TransformerFactory.newInstance().newTransformer();
        StringWriter stringOut = new StringWriter();
        Result result = new StreamResult(stringOut);
        identity.transform(source, result);

        return stringOut.toString();
    } catch (Throwable t) {
        SQLException sqlEx = SQLError.createSQLException(t.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
        sqlEx.initCause(t);

        throw sqlEx;
    }
}
项目:cas-server-4.2.1    文件:AbstractSamlObjectBuilder.java   
/**
 * Marshal the saml xml object to raw xml.
 *
 * @param object the object
 * @param writer the writer
 * @return the xml string
 */
public String marshalSamlXmlObject(final XMLObject object, final StringWriter writer)  {
    try {
        final MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
        final Marshaller marshaller = marshallerFactory.getMarshaller(object);
        if (marshaller == null) {
            throw new IllegalArgumentException("Cannot obtain marshaller for object " + object.getElementQName());
        }
        final Element element = marshaller.marshall(object);
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", SAMLConstants.SAML20_NS);
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");

        final TransformerFactory transFactory = TransformerFactory.newInstance();
        final Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(element), new StreamResult(writer));
        return writer.toString();
    } catch (final Exception e) {
        throw new IllegalStateException("An error has occurred while marshalling SAML object to xml", e);
    }
}
项目:Progetto-C    文件: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");
    }
}
项目: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;  
}
项目:joai-project    文件:CollectionAdopter.java   
/**
 *  Gets the ncsItemStream attribute of the CollectionAdopter object
 *
 * @param  nsdl_dc_stream  NOT YET DOCUMENTED
 * @return                 The ncsItemStream value
 * @exception  Exception   NOT YET DOCUMENTED
 */
public Element getNcsItemStream(Element nsdl_dc_stream) throws Exception {
    // return XSLTransformer.transformString (nsdl_dc, this.xslPath);
    String className = "net.sf.saxon.TransformerFactoryImpl";
    if (nsdl_dc_stream == null)
        return null;
    String nsdl_dc = nsdl_dc_stream.asXML();
    try {
        Transformer transformer =
            XSLTransformer.getTransformer(this.xslPath, className);
        String xml = XSLTransformer.transformString(nsdl_dc, transformer);
        if (xml != null && xml.trim().length() > 0)
            return DocumentHelper.parseText(xml).getRootElement();
    } catch (Throwable t) {
        prtln("transform problem: " + t.getMessage());
    }
    return null;
}
项目:openjdk-jdk10    文件:Bug6794483Test.java   
public String printXmlDoc(Document doc) throws Exception {
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);

    TransformerFactory transformerFact = TransformerFactory.newInstance();
    transformerFact.setAttribute("indent-number", new Integer(4));
    Transformer transformer;

    transformer = transformerFact.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");

    transformer.transform(new DOMSource(doc), result);
    return sw.toString();
}
项目:KeYExperienceReport    文件:SPLOpltionGenerator.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!");

}
项目:openjdk-jdk10    文件:CR6652519Test.java   
@Test
public final void test1() {
    try {
        long start = System.currentTimeMillis();
        Transformer t = TransformerFactory.newInstance().newTransformer();
        File file = new File(getClass().getResource("msgAttach.xml").getFile());
        StreamSource source = new StreamSource(file);
        DOMResult result = new DOMResult();
        t.transform(source, result);

        long end = System.currentTimeMillis();
        System.out.println("Test2:Total Time Taken=" + (end - start));
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
项目:stroom-stats    文件:XMLUtil.java   
public static TransformerHandler createTransformerHandler(final ErrorListener errorListener,
                                                          final boolean indentOutput) throws TransformerConfigurationException {
    final SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactoryFactory.newInstance();
    if (errorListener != null) {
        stf.setErrorListener(errorListener);
    }

    final TransformerHandler th = stf.newTransformerHandler();
    final Transformer transformer = th.getTransformer();
    setCommonOutputProperties(transformer, indentOutput);

    if (errorListener != null) {
        transformer.setErrorListener(errorListener);
    }

    return th;
}
项目:TextHIN    文件:SparqlExecutor.java   
public static void printDocument(Node node, OutputStream out) {
  try {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    transformer.transform(
        new DOMSource(node),
        new StreamResult(new OutputStreamWriter(out, "UTF-8")));
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
项目:OpenJSharp    文件:MexEntityResolver.java   
public MexEntityResolver(List<? extends Source> wsdls) throws IOException {
    Transformer transformer = XmlUtil.newTransformer();
    for (Source source : wsdls) {
        XMLStreamBufferResult xsbr = new XMLStreamBufferResult();
        try {
            transformer.transform(source, xsbr);
        } catch (TransformerException e) {
            throw new WebServiceException(e);
        }
        String systemId = source.getSystemId();

        //TODO: can we do anything if the given mex Source has no systemId?
        if(systemId != null){
            SDDocumentSource doc = SDDocumentSource.create(JAXWSUtils.getFileOrURL(systemId), xsbr.getXMLStreamBuffer());
            this.wsdls.put(systemId, doc);
        }
    }
}
项目: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 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 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/>"));
}
项目:massim    文件:Conversions.java   
/**
 * Transforms a DOM document to string.
 * @param doc the document to transform
 * @return the string representation of the doc or an empty string if sth. went wrong
 */
public static String docToString(Document doc, boolean indent){
    try {
        StringWriter writer = new StringWriter();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        if (indent) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        return writer.getBuffer().toString();
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return "";
}
项目:DaUtil    文件: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());
    }
}
项目:javaide    文件:FormatFactory.java   
private static String formatXml(Context context, String src) throws TransformerException,
        ParserConfigurationException, IOException, SAXException {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(src)));

    AppSetting setting = new AppSetting(context);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", setting.getTab().length() + "");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    //initialize StreamResult with File object to save to file
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    return result.getWriter().toString();
}
项目: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 );
}
项目:openjdk-jdk10    文件:SourceTest.java   
@Test
public final void testSAXSource() {
    String xml = getClass().getResource("SourceTest.xml").getFile();
    File xsl = new File(getClass().getResource("SourceTest.xsl").getFile());
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        StreamSource source = new StreamSource(xsl);
        transformer = tFactory.newTransformer(source);
        // the xml result
        StringWriter xmlResultString = new StringWriter();
        StreamResult xmlResultStream = new StreamResult(xmlResultString);

        Source xmlSource = new SAXSource();
        xmlSource.setSystemId(xml);

        transformer.transform(xmlSource, xmlResultStream);
        System.out.println(xmlResultString.toString());
        String temp = xmlResultString.toString();
        int pos = temp.lastIndexOf("count");
        if (temp.substring(pos + 8, pos + 9).equals("1")) {
            Assert.fail("count=1");
        } else if (temp.substring(pos + 8, pos + 9).equals("2")) {
            // expected success
            System.out.println("count=2");
        }
    } catch (Exception e) {
        // unexpected failure
        e.printStackTrace();
        Assert.fail(e.toString());
    }
}
项目:openjdk-jdk10    文件:StylesheetTest.java   
/**
 * @bug 8058152
 * Verifies that an error is reported if the xsl:import element
 * is not at the top of the stylesheet.
 * @throws TransformerConfigurationException
 */
@Test(dataProvider = "invalidImport", expectedExceptions = TransformerConfigurationException.class)
public void testInvalidImport(String xsl) throws TransformerConfigurationException {
    StringReader xsl1 = new StringReader(xsl);
    TransformerFactory factory = TransformerFactory.newInstance();
    SAXSource xslSource = new SAXSource(new InputSource(xsl1));
    Transformer transformer = factory.newTransformer(xslSource);
}
项目:RLibrary    文件:L.java   
private static void printXml(String tag, String xml, String headString) {
    if (TextUtils.isEmpty(tag)) {
        tag = TAG;
    }
    if (xml != null) {
        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);
            xml = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
        xml = headString + "\n" + xml;
    } else {
        xml = headString + "Log with null object";
    }

    printLine(tag, true);
    String[] lines = xml.split(LINE_SEPARATOR);
    for (String line : lines) {
        if (!TextUtils.isEmpty(line)) {
            Log.d(tag, "|" + line);
        }
    }
    printLine(tag, false);
}
项目:octoBubbles    文件:PersistenceManager.java   
public static void exportXMI(Graph pGraph, String path){
    try{
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        DOMSource source = new DOMSource(createXmi(pGraph));

        StreamResult result = new StreamResult(new File(path));
        transformer.transform(source, result);
    } catch (TransformerException tfe) {
        tfe.printStackTrace();
    }
}
项目:joai-project    文件:XSLTransformer.java   
/**
 *  Transforms an XML file using a pre-compiled {@link javax.xml.transform.Transformer}. Use {@link
 *  #getTransformer(String xslFilePath)} to produce a reusable {@link javax.xml.transform.Transformer} for a
 *  given XSL stylesheet. To convert the resulting StringWriter to a String, call StringWriter.toString().
 *
 * @param  inputFilePath  The XML file to transform.
 * @param  transformer    A pre-compiled {@link javax.xml.transform.Transformer} used to produce transformed
 *      output.
 * @return                A StringWriter containing the transformed content.
 */
public final static StringWriter transformFileToWriter(String inputFilePath, Transformer transformer) {
    try {
        StringWriter writer = new StringWriter();
        transformer.transform(new StreamSource(new FileInputStream(inputFilePath)), new StreamResult(writer));
        return writer;
    } catch (Throwable e) {
        prtlnErr(e);
        return new StringWriter();
    }
}
项目:nfse    文件:AssinaturaDigital.java   
private String converteDocParaXml(Document doc) throws TransformerException {
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  Transformer trans = TransformerFactory.newInstance().newTransformer();
  trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  trans.transform(new DOMSource(doc), new StreamResult(os));
  return os.toString();
}
项目:openjdk-jdk10    文件:Test.java   
private static String toString(Source response) throws TransformerException, IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(response, new StreamResult(bos));
    bos.close();
    return new String(bos.toByteArray());
}
项目:openjdk-jdk10    文件:TransformerTest.java   
@Test(dataProvider = "testdata8150704")
public void run(String xsl, String xml, String ref) throws IOException, TransformerException {
    System.out.println("Testing transformation of " + xml + "...");
    setXsl(fromInputStream(getClass().getResourceAsStream(xsl)));
    setSourceXml(fromInputStream(getClass().getResourceAsStream(xml)));
    Transformer t = getTransformer();
    StringWriter resultWriter = new StringWriter();
    t.transform(getStreamSource(), new StreamResult(resultWriter));
    String resultString = resultWriter.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n").trim();
    String reference = fromInputStream(getClass().getResourceAsStream(ref)).trim();
    Assert.assertEquals(resultString, reference, "Output of transformation of " + xml + " does not match reference");
    System.out.println("Passed.");
}