javax.xml.transform.Transformer#setOutputProperty ( )源码实例Demo

下面列出了javax.xml.transform.Transformer#setOutputProperty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: freehealth-connector   文件: ConnectorXmlUtils.java
public static String format(String unformattedXml, Source xslt) {
   try {
      Document doc = parseXmlFile(unformattedXml);
      DOMSource domSource = new DOMSource(doc);
      StringWriter writer = new StringWriter();
      StreamResult result = new StreamResult(writer);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = null;
      if (xslt != null) {
         transformer = tf.newTransformer(xslt);
      } else {
         transformer = tf.newTransformer();
      }

      transformer.setOutputProperty("indent", "yes");
      transformer.setOutputProperty("omit-xml-declaration", "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(1));
      transformer.transform(domSource, result);
      return writer.toString();
   } catch (Exception var8) {
      throw new InstantiationException(var8);
   }
}
 
源代码2 项目: JVoiceXML   文件: XmlDocument.java
/**
 * Writes the state of the object for its particular class so that the
 * corresponding {@link #readObject(java.io.ObjectInputStream)}
 * method can restore it.
 * @param out the stream to write to
 * @throws IOException
 *         if an error occurs while writing to the stream
 */
private void writeObject(final ObjectOutputStream out)
    throws IOException {
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    final Result result = new StreamResult(buffer);
    final TransformerFactory transformerFactory =
        TransformerFactory.newInstance();
    try {
        final Transformer transformer = transformerFactory.newTransformer();
        final String encoding = System.getProperty("jvoicexml.xml.encoding",
            "UTF-8");
        transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
        final Source source = new DOMSource(this);
        transformer.transform(source, result);
    } catch (TransformerException e) {
        throw new IOException(e.getMessage(), e);
    }
    out.writeLong(buffer.size());
    out.write(buffer.toByteArray());
}
 
源代码3 项目: journaldev   文件: XmlFormatter.java
public static String prettyFormat(String input, String indent) {
	Source xmlInput = new StreamSource(new StringReader(input));
	StringWriter stringWriter = new StringWriter();
	try {
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", indent);
		transformer.transform(xmlInput, new StreamResult(stringWriter));

		return stringWriter.toString().trim();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
源代码4 项目: eclair   文件: XPathMasker.java
@Override
public String process(String string) {
    if (xPathExpressions.isEmpty()) {
        return string;
    }
    InputStream stream = new ByteArrayInputStream(string.getBytes());
    try {
        Document document = documentBuilderFactory.newDocumentBuilder().parse(stream);
        XPath xPath = xPathfactory.newXPath();
        for (String xPathExpression : xPathExpressions) {
            NodeList nodeList = (NodeList) xPath.compile(xPathExpression).evaluate(document, XPathConstants.NODESET);
            for (int a = 0; a < nodeList.getLength(); a++) {
                nodeList.item(a).setTextContent(replacement);
            }
        }
        StringWriter writer = new StringWriter();
        Transformer transformer = transformerFactory.newTransformer();
        for (Map.Entry<String, String> entry : outputProperties.entrySet()) {
            transformer.setOutputProperty(entry.getKey(), entry.getValue());
        }
        transformer.transform(new DOMSource(document), new StreamResult(writer));
        return writer.getBuffer().toString();
    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | TransformerException e) {
        throw new IllegalArgumentException(e);
    }
}
 
源代码5 项目: packagedrone   文件: XmlHelper.java
public static void write ( final TransformerFactory transformerFactory, final Node node, final Result result, final Consumer<Transformer> transformerCustomizer ) throws TransformerException
{
    final Transformer transformer = transformerFactory.newTransformer ();
    final DOMSource source = new DOMSource ( node );

    transformer.setOutputProperty ( OutputKeys.INDENT, "yes" );
    transformer.setOutputProperty ( OutputKeys.ENCODING, "UTF-8" );
    transformer.setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount", "2" );

    if ( transformerCustomizer != null )
    {
        transformerCustomizer.accept ( transformer );
    }

    transformer.transform ( source, result );
}
 
源代码6 项目: sc2gears   文件: ParsingServlet.java
/**
 * Prints the document to the specified HTTP servlet response.
 * @param response response to print the document to
 */
public void printDocument( final HttpServletResponse response ) throws TransformerFactoryConfigurationError, TransformerException, IOException {
	response.setContentType( "text/xml" );
	response.setCharacterEncoding( "UTF-8" );
	setNoCache( response );
	
	final Transformer transformer = TransformerFactory.newInstance().newTransformer();
	transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );
	transformer.transform( new DOMSource( document ), new StreamResult( response.getOutputStream() ) );
}
 
源代码7 项目: jdk8u_jdk   文件: JDK8207760.java
@Test(dataProvider = "xsls")
public final void testBug8207760_cdata(String xsl) throws Exception {
    String[] xmls = prepareXML(true);
    Transformer t = createTransformerFromInputstream(
            new ByteArrayInputStream(xsl.getBytes(StandardCharsets.UTF_8)));
    t.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
    StringWriter sw = new StringWriter();
    t.transform(new StreamSource(new StringReader(xmls[0])), new StreamResult(sw));
    Assert.assertEquals(sw.toString().replaceAll(System.lineSeparator(), "\n"), xmls[1]);
}
 
源代码8 项目: Cynthia   文件: XMLUtil.java
/**
 * @description:transfer document to string 
 * @date:2014-11-11 下午4:09:14
 * @version:v1.0
 * @param document
 * @param encode
 * @return
 * @throws TransformerException
 */
public static String document2String(Document document, String encode) throws TransformerException
{
    String xml = null;
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    DOMSource source = new DOMSource(document);
    transformer.setOutputProperty("encoding", encode);
    transformer.setOutputProperty("indent", "yes");
    StringWriter sw = new StringWriter();
    transformer.transform(source, new StreamResult(sw));
    xml = sw.toString();
    return xml;
}
 
源代码9 项目: zap-extensions   文件: ReportGenerator.java
public static String getDebugXMLString(Document doc) throws TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    return writer.getBuffer().toString().replaceAll("\n|\r", "");
}
 
源代码10 项目: TencentKona-8   文件: SaajEmptyNamespaceTest.java
private String nodeToText(Node node) throws TransformerException {
    Transformer trans = TransformerFactory.newInstance().newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    trans.transform(new DOMSource(node), result);
    String bodyContent = writer.toString();
    System.out.println("SOAP body content read by SAAJ:"+bodyContent);
    return bodyContent;
}
 
源代码11 项目: jdk8u-jdk   文件: SaajEmptyNamespaceTest.java
private String nodeToText(Node node) throws TransformerException {
    Transformer trans = TransformerFactory.newInstance().newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    trans.transform(new DOMSource(node), result);
    String bodyContent = writer.toString();
    System.out.println("SOAP body content read by SAAJ:"+bodyContent);
    return bodyContent;
}
 
源代码12 项目: jeka   文件: JkUtilsXml.java
/**
 * Prints the specified document in the specified output getOutputStream.
 * The output is indented.
 */
public static void output(Document doc, OutputStream outputStream) {
    Transformer transformer;
    try {
        transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        final DOMSource source = new DOMSource(doc);
        final StreamResult console = new StreamResult(outputStream);
        transformer.transform(source, console);
    } catch (final Exception e) {
        throw JkUtilsThrowable.unchecked(e);
    }
}
 
源代码13 项目: netbeans   文件: XMLUtil.java
public static void write(Element el, OutputStream out) throws IOException {
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer(
                new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        Source source = new DOMSource(el);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (Exception | TransformerFactoryConfigurationError e) {
        throw new IOException(e);
    }
}
 
@Before
public void setUp()
{   
    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.STANDALONE, "no");

    writer = new StringWriter();
    xmlOut.setResult(new StreamResult(writer));
    
    transformer = new DbObjectXMLTransformer(xmlOut);        
}
 
源代码15 项目: gank   文件: LogUtil.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);
}
 
源代码16 项目: uima-uimaj   文件: XMLSerializerTest.java
public void testXml11() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLSerializer sax2xml = new XMLSerializer(baos, false);
    sax2xml.setOutputProperty(OutputKeys.VERSION, "1.1");
    ContentHandler ch = sax2xml.getContentHandler();    
    ch.startDocument();
    ch.startElement("","foo","foo", new AttributesImpl());
    ch.endElement("", "foo", "foo");
    ch.endDocument();
    String xmlStr = new String(baos.toByteArray(), StandardCharsets.UTF_8);
//    if (xmlStr.contains("1.0")) {
    // useful to investigate issues when bad XML output is produced
    //   related to which Java implementation is being used
      TransformerFactory transformerFactory = XMLUtils.createTransformerFactory();
      Transformer t = transformerFactory.newTransformer();
      t.setOutputProperty(OutputKeys.VERSION, "1.1");
      
      System.out.println("Java version is " + 
                            System.getProperty("java.vendor") + " " +
                            System.getProperty("java.version") + " " +
                            System.getProperty("java.vm.name") + " " +
                            System.getProperty("java.vm.version") + 
                         "\n  javax.xml.transform.TransformerFactory: " +
                            System.getProperty("javax.xml.transform.TransformerFactory") + 
                         "\n  Transformer version: " +
                            t.getOutputProperty(OutputKeys.VERSION));
//    }
    assertEquals("<?xml version=\"1.1\" encoding=\"UTF-8\"?><foo/>", xmlStr);
  }
 
源代码17 项目: concierge   文件: PojoReflector.java
@SuppressWarnings("unused")
private final String printDoc(final Document doc) throws Exception {
	TransformerFactory tf = TransformerFactory.newInstance();
	Transformer transformer = tf.newTransformer();
	transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	StringWriter writer = new StringWriter();
	transformer.transform(new DOMSource(doc), new StreamResult(writer));
	return writer.getBuffer().toString();
}
 
源代码18 项目: staedi   文件: StaEDIXMLStreamReaderTest.java
@Test
void testEDIReporterSet() throws Exception {
    EDIInputFactory ediFactory = EDIInputFactory.newFactory();
    Map<String, Set<EDIStreamValidationError>> errors = new LinkedHashMap<>();
    ediFactory.setEDIReporter((errorEvent, reader) -> {
        Location location = reader.getLocation();
        String key;

        if (location.getElementPosition() > 0) {
            key = String.format("%s%[email protected]%d",
                                location.getSegmentTag(),
                                location.getElementPosition(),
                                location.getSegmentPosition());
        } else {
            key = String.format("%[email protected]%d",
                                location.getSegmentTag(),
                                location.getSegmentPosition());
        }

        if (!errors.containsKey(key)) {
            errors.put(key, new HashSet<EDIStreamValidationError>(2));
        }

        errors.get(key).add(errorEvent);
    });
    InputStream stream = getClass().getResourceAsStream("/x12/invalid999.edi");
    SchemaFactory schemaFactory = SchemaFactory.newFactory();
    Schema schema = schemaFactory.createSchema(getClass().getResource("/x12/EDISchema999.xml"));

    EDIStreamReader ediReader = ediFactory.createEDIStreamReader(stream);
    ediReader = ediFactory.createFilteredReader(ediReader, (reader) -> {
        if (reader.getEventType() == EDIStreamEvent.START_TRANSACTION) {
            reader.setTransactionSchema(schema);
        }
        return true;
    });

    XMLStreamReader xmlReader = new StaEDIXMLStreamReader(ediReader);

    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();
    System.out.println("Errors: " + errors);
    System.out.println(resultString);

    Iterator<Entry<String, Set<EDIStreamValidationError>>> errorSet = errors.entrySet().iterator();
    Entry<String, Set<EDIStreamValidationError>> error = errorSet.next();
    assertEquals("[email protected]", error.getKey());
    assertEquals(EDIStreamValidationError.UNEXPECTED_SEGMENT, error.getValue().iterator().next());
    error = errorSet.next();
    assertEquals("[email protected]", error.getKey());
    assertEquals(EDIStreamValidationError.DATA_ELEMENT_TOO_LONG, error.getValue().iterator().next());
    error = errorSet.next();
    assertEquals("[email protected]", error.getKey());
    assertEquals(EDIStreamValidationError.TOO_MANY_DATA_ELEMENTS, error.getValue().iterator().next());
    error = errorSet.next();
    assertEquals("[email protected]", error.getKey());
    assertEquals(EDIStreamValidationError.TOO_MANY_DATA_ELEMENTS, error.getValue().iterator().next());
    error = errorSet.next();
    assertEquals("[email protected]", error.getKey());
    assertEquals(EDIStreamValidationError.INVALID_CODE_VALUE, error.getValue().iterator().next());
    error = errorSet.next();
    assertEquals("[email protected]", error.getKey());
    assertEquals(EDIStreamValidationError.SEGMENT_EXCEEDS_MAXIMUM_USE, error.getValue().iterator().next());

    Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/invalid999_transformed.xml"))
                        .withTest(resultString).build();
    assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter()));
}
 
@Test
public void testBulkLoadWithXSLTClientSideTransform() throws KeyManagementException, NoSuchAlgorithmException, Exception {
  String docId[] = { "/transform/emp.xml", "/transform/food1.xml", "/transform/food2.xml" };
  Source s[] = new Source[3];
  Scanner scanner=null, sc1 = null, sc2 = null;
  s[0] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/employee.xml");
  s[1] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/xml-original.xml");
  s[2] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/xml-original-test.xml");
  // get the xslt
  Source xsl = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/employee-stylesheet.xsl");

  // create transformer
  TransformerFactory factory = TransformerFactory.newInstance();
  Transformer transformer = factory.newTransformer(xsl);
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");

  XMLDocumentManager docMgr = client.newXMLDocumentManager();
  DocumentWriteSet writeset = docMgr.newWriteSet();
  for (int i = 0; i < 3; i++) {
    SourceHandle handle = new SourceHandle();
    handle.set(s[i]);
    // set the transformer
    handle.setTransformer(transformer);
    writeset.add(docId[i], handle);
    // Close handle.
    handle.close();
  }
  docMgr.write(writeset);
  FileHandle dh = new FileHandle();
  
  try {
  docMgr.read(docId[0], dh);
  scanner = new Scanner(dh.get()).useDelimiter("\\Z");
  String readContent = scanner.next();
  assertTrue("xml document contains firstname", readContent.contains("firstname"));
  docMgr.read(docId[1], dh);
  sc1 = new Scanner(dh.get()).useDelimiter("\\Z");
  readContent = sc1.next();
  assertTrue("xml document contains firstname", readContent.contains("firstname"));
  docMgr.read(docId[2], dh);
  sc2 = new Scanner(dh.get()).useDelimiter("\\Z");
  readContent = sc2.next();
  assertTrue("xml document contains firstname", readContent.contains("firstname"));
  }
  catch (Exception e) {
  	e.printStackTrace();
  }
  finally {
  	scanner.close();
  	sc1.close();
  	sc2.close();
  }

}
 
源代码20 项目: mzmine2   文件: UserParameterSaveHandler.java
/**
 * Function which creates an XML file with user parameters
 */
void saveParameters() throws SAXException, IOException, TransformerConfigurationException {

  logger.info("Saving user parameters");

  StreamResult streamResult = new StreamResult(finalStream);
  SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

  TransformerHandler hd = tf.newTransformerHandler();

  Transformer serializer = hd.getTransformer();
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

  hd.setResult(streamResult);
  hd.startDocument();

  UserParameter<?, ?> projectParameters[] = project.getParameters();

  AttributesImpl atts = new AttributesImpl();

  atts.addAttribute("", "", UserParameterElementName.COUNT.getElementName(), "CDATA",
      String.valueOf(projectParameters.length));

  hd.startElement("", "", UserParameterElementName.PARAMETERS.getElementName(), atts);

  atts.clear();

  // <PARAMETER>
  for (UserParameter<?, ?> parameter : project.getParameters()) {

    if (canceled)
      return;

    logger.finest("Saving user parameter " + parameter.getName());

    atts.addAttribute("", "", UserParameterElementName.NAME.getElementName(), "CDATA",
        parameter.getName());

    atts.addAttribute("", "", UserParameterElementName.TYPE.getElementName(), "CDATA",
        parameter.getClass().getSimpleName());

    hd.startElement("", "", UserParameterElementName.PARAMETER.getElementName(), atts);

    atts.clear();

    fillParameterElement(parameter, hd);

    hd.endElement("", "", UserParameterElementName.PARAMETER.getElementName());
    completedParameters++;
  }

  hd.endElement("", "", UserParameterElementName.PARAMETERS.getElementName());

  hd.endDocument();

}