Java Code Examples for javax.xml.transform.Transformer.setOutputProperty()

The following are Jave code examples for showing how to use setOutputProperty() of the javax.xml.transform.Transformer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GitHub   File: DefaultXmlFormatter.java   View Source Code Vote up 6 votes
@Override
public String format(String xml) {
  String formattedString;
  if (xml == null || xml.trim().length() == 0) {
    throw new FormatException("XML empty.");
  }
  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);
    formattedString = xmlOutput.getWriter().toString().replaceFirst(">", ">"
        + SystemCompat.lineSeparator);
  } catch (Exception e) {
    throw new FormatException("Parse XML error. XML string:" + xml, e);
  }
  return formattedString;
}
 
Example 2
Project: VASSAL-src   File: Builder.java   View Source Code Vote up 6 votes
/**
 * 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);
  }
}
 
Example 3
Project: bdf2   File: GraphicalEditorPage.java   View Source Code Vote up 6 votes
public void synchroGraphicalToXml(){
	Document doc=this.buildDocument();
	if(doc==null)return;
	TransformerFactory factory=TransformerFactory.newInstance();
	try{
		Transformer transformer=factory.newTransformer();
		transformer.setOutputProperty("encoding","utf-8");
		transformer.setOutputProperty(OutputKeys.INDENT,"yes");				
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		transformer.transform(new DOMSource(doc),new StreamResult(out));
		xmlEditor.getDocumentProvider().getDocument(xmlEditor.getEditorInput()).set(out.toString("utf-8"));
		out.close();
	}catch(Exception ex){
		ex.printStackTrace();
	}
}
 
Example 4
Project: sierra   File: XmlOutput.java   View Source Code Vote up 6 votes
@Override
public String toString() {
	try {
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");

		DOMSource source = new DOMSource(document);
		StreamResult result = new StreamResult(new StringWriter());
		transformer.transform(source, result);
		return result.getWriter().toString();
	} catch (TransformerException e) {
		throw new RuntimeException(e);
	}
}
 
Example 5
Project: TextHIN   File: SparqlExecutor.java   View Source Code Vote up 6 votes
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);
  }
}
 
Example 6
Project: KUtils   File: XmlLog.java   View Source Code Vote up 5 votes
private static String formatXML(String inputXML) {
    try {
        Source xmlInput = new StreamSource(new StringReader(inputXML));
        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);
        return xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
    } catch (Exception e) {
        e.printStackTrace();
        return inputXML;
    }
}
 
Example 7
Project: trashjam2017   File: ParticleIO.java   View Source Code Vote up 5 votes
/**
 * 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");
	}
}
 
Example 8
Project: stroom-stats   File: XMLUtil.java   View Source Code Vote up 5 votes
public static void setCommonOutputProperties(final Transformer transformer, final boolean indentOutput)
        throws TransformerConfigurationException {
    transformer.setOutputProperty(OutputKeys.METHOD, XML);
    transformer.setOutputProperty(OutputKeys.ENCODING, UTF_8);
    transformer.setOutputProperty(OutputKeys.VERSION, VERSION);
    if (indentOutput) {
        transformer.setOutputProperty(OutputKeys.INDENT, YES);
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
    } else {
        transformer.setOutputProperty(OutputKeys.INDENT, NO);
    }
}
 
Example 9
Project: javaide   File: Util.java   View Source Code Vote up 5 votes
/**
 * @source http://stackoverflow.com/a/7373596
 */
public static void writeXml(Document dom, File xmlFile) throws Exception {
    Transformer t = tf.newTransformer();
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty(OutputKeys.METHOD, "xml");
    t.setOutputProperty(OutputKeys.VERSION, "1.0");
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    t.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(xmlFile)));
}
 
Example 10
Project: UaicNlpToolkit   File: Utils.java   View Source Code Vote up 5 votes
public static void writeDocument(Document doc, OutputStream stream) throws TransformerException, IOException {
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer serializer;

    serializer = tfactory.newTransformer();
    //Setup indenting to "pretty print"
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    serializer.transform(new DOMSource(doc), new StreamResult(stream));
    stream.close();
}
 
Example 11
Project: jaffa-framework   File: TransformationHelper.java   View Source Code Vote up 5 votes
private static String nodeToString(Node node, StringWriter xmlString) throws Exception, RuntimeException {
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    t.setOutputProperty(OutputKeys.INDENT, "no");
    t.transform(new DOMSource(node), new StreamResult(xmlString));
    return xmlString.toString();
}
 
Example 12
Project: jdk8u-jdk   File: SaajEmptyNamespaceTest.java   View Source Code Vote up 5 votes
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;
}
 
Example 13
Project: DexFixDemo   File: L.java   View Source Code Vote up 5 votes
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);
}
 
Example 14
Project: oscm   File: XMLValidation.java   View Source Code Vote up 5 votes
private static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
    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");
    OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
    StreamResult sr = new StreamResult(osw);
    transformer.transform(new DOMSource(doc), 
               sr);
}
 
Example 15
Project: apache-tomcat-7.0.73-with-comment   File: DomUtil.java   View Source Code Vote up 5 votes
public static void writeXml( Node n, OutputStream os )
        throws TransformerException
{
    TransformerFactory tf=TransformerFactory.newInstance();
    //identity
    Transformer t=tf.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.transform(new DOMSource( n ), new StreamResult( os ));
}
 
Example 16
Project: GrowingProject   File: LogUtils.java   View Source Code Vote up 5 votes
private static String formatXml(String xml) {
    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", "4");
        transformer.transform(xmlInput, xmlOutput);
        xml = xmlOutput.getWriter().toString().replaceFirst(">", ">" + LINE_SEP);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return xml;
}
 
Example 17
Project: lams   File: DomUtil.java   View Source Code Vote up 5 votes
public static void writeXml( Node n, OutputStream os )
        throws TransformerException
{
    TransformerFactory tf=TransformerFactory.newInstance();
    //identity
    Transformer t=tf.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.transform(new DOMSource( n ), new StreamResult( os ));
}
 
Example 18
Project: Equella   File: XsltServiceImpl.java   View Source Code Vote up 4 votes
/**
 * Performs the XSLT transformation, possibly using a pre-compiled version.
 * Note: Does not close the supplied source
 */
private String transformFromFileHandle(final FileHandle handle, final String xslt, final StreamSource source,
	final URIResolver resolver, boolean omitXmlDeclaration)
{
	StreamSource xsltStream = null;
	Thread currentThread = Thread.currentThread();
	ClassLoader oldLoader = currentThread.getContextClassLoader();
	currentThread.setContextClassLoader(getClass().getClassLoader());
	try
	{
		Pair<Long, Templates> compiledXslt = null;
		Templates templates = null;
		final String key = getKey(handle, xslt);
		synchronized( xsltCache )
		{
			final long modified = fileSystemService.lastModified(handle, xslt);
			compiledXslt = xsltCache.get(key);
			if( compiledXslt != null )
			{
				if( compiledXslt.getFirst() != modified )
				{
					compiledXslt = null;
				}
				else
				{
					templates = compiledXslt.getSecond();
				}
			}

			if( compiledXslt == null )
			{
				xsltStream = getSource(fileSystemService.read(handle, xslt));
				templates = factory.newTemplates(xsltStream);
				xsltCache.put(key, new Pair<Long, Templates>(modified, templates));
			}
		}
		// Not sure it can be
		if( templates == null )
		{
			throw new Error("templates is null");
		}
		Transformer transformersMoreThanMeetsTheEye = templates.newTransformer();
		transformersMoreThanMeetsTheEye.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
			omitXmlDeclaration ? "yes" : "no");
		return doTransform(transformersMoreThanMeetsTheEye, source, resolver);
	}
	catch( final Exception ex )
	{
		throw new RuntimeException("Error compiling XSLT", ex);
	}
	finally
	{
		closeSource(xsltStream);
		currentThread.setContextClassLoader(oldLoader);
	}
}
 
Example 19
Project: BaseClient   File: ParticleIO.java   View Source Code Vote up 4 votes
/**
 * Save a particle system with only ConfigurableEmitters in to an XML file
 * 
 * @param out
 *            The location to which we'll save
 * @param system
 *            The system to store
 * @throws IOException
 *             Indicates a failure to save or encode the system XML.
 */
public static void saveConfiguredSystem(OutputStream out,
		ParticleSystem system) throws IOException {
	try {
		DocumentBuilder builder = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder();
		Document document = builder.newDocument();

		Element root = document.createElement("system");
		root
				.setAttribute(
						"additive",
						""
								+ (system.getBlendingMode() == ParticleSystem.BLEND_ADDITIVE));
		root.setAttribute("points", "" + (system.usePoints()));

		document.appendChild(root);
		for (int i = 0; i < system.getEmitterCount(); i++) {
			ParticleEmitter current = system.getEmitter(i);
			if (current instanceof ConfigurableEmitter) {
				Element element = emitterToElement(document,
						(ConfigurableEmitter) current);
				root.appendChild(element);
			} else {
				throw new RuntimeException(
						"Only ConfigurableEmitter instances can be stored");
			}
		}

		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("Unable to save configured particle system");
	}
}
 
Example 20
Project: Compiler   File: GScanner.java   View Source Code Vote up 4 votes
public static void saveToXML(String oXMLFile) {
    String[] strsPath = oXMLFile.split("/");
    String strsProject = strsPath[strsPath.length-1];

    String[] strs = strsProject.split("\\."); // or "[.]"
    String projectName = strs[0];
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();


        // root
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("project");
        rootElement.setAttribute("name", projectName);

        doc.appendChild(rootElement);

        Element subRootElement = doc.createElement("tokens");
        rootElement.appendChild(subRootElement);

        for (int i = 0; i < tokenLab.size(); i++) {
            Element tokenElement = doc.createElement("token");
            // number
            Element numberElement = doc.createElement("number");
            numberElement.appendChild(doc.createTextNode(String.valueOf(tokenLab.get(i).number)));
            tokenElement.appendChild(numberElement);

            // line
            Element lineElement = doc.createElement("line");
            lineElement.appendChild(doc.createTextNode(String.valueOf(tokenLab.get(i).line)));
            tokenElement.appendChild(lineElement);

            // value
            Element valueElement = doc.createElement("value");
            valueElement.appendChild(doc.createTextNode(tokenLab.get(i).value));
            tokenElement.appendChild(valueElement);

            // type
            Element typeElement = doc.createElement("type");
            typeElement.appendChild(doc.createTextNode(typeIntToString(tokenLab.get(i).type)));
            tokenElement.appendChild(typeElement);

            // valid
            Element validElement = doc.createElement("valid");
            validElement.appendChild(doc.createTextNode(String.valueOf(tokenLab.get(i).isValid)));
            tokenElement.appendChild(validElement);

            subRootElement.appendChild(tokenElement);
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(oXMLFile));

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

        transformer.transform(source, result);

        System.out.println("File saved!");
    } catch (Exception e) {
        e.printStackTrace();
    }

}