本文整理了Java中javax.xml.transform.Transformer
类的一些代码示例,展示了Transformer
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Transformer
类的具体详情如下:
包路径:javax.xml.transform.Transformer
类名称:Transformer
[英]An instance of this abstract class can transform a source tree into a result tree.
An instance of this class can be obtained with the TransformerFactory#newTransformermethod. This instance may then be used to process XML from a variety of sources and write the transformation output to a variety of sinks.
An object of this class may not be used in multiple threads running concurrently. Different Transformers may be used concurrently by different threads.
A Transformer
may be used multiple times. Parameters and output properties are preserved across transformations.
[中]这个抽象类的实例可以将源树转换为结果树。
可以使用TransformerFactory#newTransformermethod获得此类的实例。然后,可以使用该实例处理来自各种源的XML,并将转换输出写入各种接收器。
此类的对象不能用于同时运行的多个线程中。不同的线程可以同时使用不同的变压器。Transformer
可以多次使用。参数和输出属性在转换过程中保持不变。
代码示例来源:origin: stackoverflow.com
public 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");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc),
new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}
代码示例来源:origin: org.apache.ant/ant
/**
* Sets the parameters for the transformer.
*/
private void setTransformationParameters() {
params.forEach((key, value) -> transformer.setParameter(key, value));
}
代码示例来源:origin: stackoverflow.com
DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());
代码示例来源:origin: apache/nifi
@Override
public String getFingerprint() throws AuthorizationAccessException {
final StringWriter out = new StringWriter();
try {
// create the document
final DocumentBuilder documentBuilder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
final Document document = documentBuilder.newDocument();
// create the root element
final Element managedRangerAuthorizationsElement = document.createElement("managedRangerAuthorizations");
document.appendChild(managedRangerAuthorizationsElement);
// create the user group provider element
final Element userGroupProviderElement = document.createElement(USER_GROUP_PROVIDER_ELEMENT);
managedRangerAuthorizationsElement.appendChild(userGroupProviderElement);
// append fingerprint if the provider is configurable
if (userGroupProvider instanceof ConfigurableUserGroupProvider) {
userGroupProviderElement.appendChild(document.createTextNode(((ConfigurableUserGroupProvider) userGroupProvider).getFingerprint()));
}
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(out));
} catch (ParserConfigurationException | TransformerException e) {
throw new AuthorizationAccessException("Unable to generate fingerprint", e);
}
return out.toString();
}
代码示例来源:origin: BroadleafCommerce/BroadleafCommerce
File statusFile = getStatusFile((SolrSearchServiceImpl) searchService);
boolean exists = statusFile.exists();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
updateDeadEventSegment(document, rootElement, status, clearDeadEvents);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer xmlTransformer = tFactory.newTransformer();
xmlTransformer.setOutputProperty(OutputKeys.VERSION, "1.0");
xmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(statusFile, false), "UTF-8"));
StreamResult result = new StreamResult(writer);
xmlTransformer.transform(source, result);
} finally {
if (writer != null) {
代码示例来源:origin: xalan/xalan
transformer.setErrorListener(new DefaultErrorHandler(false));
transformer.setOutputProperty(OutputKeys.METHOD, outputType);
transformer.setParameter((String) params.elementAt(i),
(String) params.elementAt(i + 1));
transformer.setURIResolver(uriResolver);
transformer.transform(new DOMSource(xmlDoc, inFileName),
new DOMResult(outNode));
serializer.setErrorListener(new DefaultErrorHandler(false));
serializer.setOutputProperties(serializationProps);
serializer.transform(new DOMSource(outNode), result);
serializer.transform(new DOMSource(outNode), strResult);
transformer.transform(
new SAXSource(reader, new InputSource(inFileName)),
result);
transformer.transform(
new SAXSource(reader, new InputSource(inFileName)),
strResult);
transformer.transform(new StreamSource(inFileName), result);
代码示例来源:origin: jphp-group/jphp
protected void write(CommandArguments args, AbstractCommand command) {
try {
Document document = xmlBuilder.newDocument();
command.run(this, args, document);
StringWriter xmlWriter = new StringWriter();
StreamResult xmlResult = new StreamResult(xmlWriter);
transformer.transform(new DOMSource(document), xmlResult);
byte[] xmlBytes = xmlWriter.toString().getBytes();
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
out.write(String.valueOf(xmlBytes.length).getBytes());
out.write("\0".getBytes());
out.write(xmlBytes);
out.write("\0".getBytes());
out.flush();
} catch (IOException | TransformerException e) {
throw new DebuggerException(e);
}
}
代码示例来源:origin: spring-projects/spring-framework
@Test
public void streamReaderSourceToStreamResult() throws Exception {
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(XML));
StaxSource source = new StaxSource(streamReader);
assertEquals("Invalid streamReader returned", streamReader, source.getXMLStreamReader());
assertNull("EventReader returned", source.getXMLEventReader());
StringWriter writer = new StringWriter();
transformer.transform(source, new StreamResult(writer));
assertThat("Invalid result", writer.toString(), isSimilarTo(XML));
}
代码示例来源:origin: xalan/xalan
StringWriter osw = new StringWriter();
PrintWriter pw = new PrintWriter(osw, false);
StreamResult result = new StreamResult(pw);
StreamSource xslSource = new StreamSource(styleURL.toString());
Transformer transformer = m_tfactory.newTransformer(xslSource);
Object key = entry.getKey();
Object expression = entry.getValue();
transformer.setParameter((String) key, expression);
transformer.transform(xmlSource, result);
htmlData = osw.toString();
代码示例来源:origin: spring-projects/spring-framework
@Test
public void streamWriterSource() throws Exception {
StringWriter stringWriter = new StringWriter();
XMLStreamWriter streamWriter = inputFactory.createXMLStreamWriter(stringWriter);
Reader reader = new StringReader(XML);
Source source = new StreamSource(reader);
StaxResult result = new StaxResult(streamWriter);
assertEquals("Invalid streamWriter returned", streamWriter, result.getXMLStreamWriter());
assertNull("EventWriter returned", result.getXMLEventWriter());
transformer.transform(source, result);
assertThat("Invalid result", stringWriter.toString(), isSimilarTo(XML));
}
代码示例来源:origin: apache/cxf
private String transformLocally(Message m, UriInfo ui, Source source) throws Exception {
InputStream is = ResourceUtils.getResourceStream(stylesheetReference, m.getExchange().getBus());
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = transformerFactory.newTemplates(new StreamSource(is)).newTransformer();
t.setParameter("base.path", m.get("http.base.path"));
StringWriter stringWriter = new StringWriter();
t.transform(source, new StreamResult(stringWriter));
return stringWriter.toString();
}
代码示例来源:origin: pentaho/mondrian
dfactory.setNamespaceAware(true);
DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
Node xslDOM = docBuilder.parse(new InputSource(xslReader));
Templates stylesheet = tfactory.newTemplates(new DOMSource(xslDOM));
Transformer transformer = stylesheet.newTransformer();
if (namevalueParameters != null) {
String value = namevalueParameters[i][1];
transformer.setParameter(name, value);
transformer.transform(new DOMSource(inDoc, null), domResult);
代码示例来源:origin: pmd/pmd
private void transform(Document doc) {
DOMSource source = new DOMSource(doc);
this.setWriter(new StringWriter());
StreamResult result = new StreamResult(this.outputWriter);
try {
transformer.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
}
}
代码示例来源:origin: geoserver/geoserver
public void testEncode() throws Exception {
Ows10Factory f = Ows10Factory.eINSTANCE;
GetCapabilitiesType caps = f.createGetCapabilitiesType();
AcceptVersionsType versions = f.createAcceptVersionsType();
caps.setAcceptVersions(versions);
versions.getVersion().add("1.0.0");
versions.getVersion().add("1.1.0");
ByteArrayOutputStream output = new ByteArrayOutputStream();
response.write(caps, output, null);
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
TransformerFactory.newInstance()
.newTransformer()
.transform(
new StreamSource(new ByteArrayInputStream(output.toByteArray())),
new DOMResult(d));
assertEquals("ows:GetCapabilities", d.getDocumentElement().getNodeName());
assertEquals(2, d.getElementsByTagName("ows:Version").getLength());
}
}
代码示例来源:origin: marytts/marytts
public MaryData process(MaryData d) throws Exception {
DOMSource domSource = new DOMSource(d.getDocument());
Transformer transformer = stylesheet.newTransformer();
// Log transformation errors to client:
if (doWarnClient) {
// Use custom error handler:
transformer.setErrorListener(new LoggingErrorHandler(Thread.currentThread().getName() + " client.Sable transformer"));
}
// Transform DOMSource into a DOMResult
Document maryxmlDocument = docBuilder.newDocument();
DOMResult domResult = new DOMResult(maryxmlDocument);
transformer.transform(domSource, domResult);
MaryData result = new MaryData(outputType(), d.getLocale());
result.setDocument(maryxmlDocument);
return result;
}
}
代码示例来源:origin: jphp-group/jphp
@Signature(@Arg(value = "flags", optional = @Optional("0")))
public Memory __construct(final Environment env, Memory... args) throws ParserConfigurationException, TransformerConfigurationException {
transformerFactory = TransformerFactory.newInstance();
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
builderFactory = DocumentBuilderFactory.newInstance();
builder = builderFactory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException exception) throws SAXException {
代码示例来源:origin: pentaho/pentaho-kettle
data.factory = TransformerFactory.newInstance();
transformer.setOutputProperties( data.outputProperties );
transformer.setParameter( data.nameOfParams[i], row[data.indexOfParams[i]] );
StreamResult result = new StreamResult( new StringWriter() );
transformer.transform( source, result );
String xmlString = result.getWriter().toString();
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "Xslt.Log.FileResult" ) );
代码示例来源:origin: wildfly/wildfly
public InputStream sanitize(InputStream in) throws Exception {
byte [] content = IOUtils.toByteArray(in);
try {
// storing the entire file in memory in case we need to bail.
Document doc = builder.parse(new ByteArrayInputStream(content));
doc.setXmlStandalone(true);
Object result = expression.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
nodes.item(i).setTextContent("");
}
DOMSource source = new DOMSource(doc);
ByteArrayOutputStream output = new ByteArrayOutputStream();
StreamResult outStream = new StreamResult(output);
transformer.transform(source, outStream);
return new ByteArrayInputStream(output.toByteArray());
} catch (Exception e) {
ROOT_LOGGER.debug("Error while sanitizing an xml document", e);
return new ByteArrayInputStream(content);
}
}
}
代码示例来源:origin: pentaho/pentaho-kettle
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (AddXMLMeta) smi;
data = (AddXMLData) sdi;
if ( !super.init( smi, sdi ) ) {
return false;
}
try {
setSerializer( TransformerFactory.newInstance().newTransformer() );
setDomImplentation( XMLParserFactoryProducer.createSecureDocBuilderFactory().newDocumentBuilder().getDOMImplementation() );
if ( meta.getEncoding() != null ) {
getSerializer().setOutputProperty( OutputKeys.ENCODING, meta.getEncoding() );
}
if ( meta.isOmitXMLheader() ) {
getSerializer().setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
}
} catch ( TransformerConfigurationException e ) {
return false;
} catch ( ParserConfigurationException e ) {
return false;
}
return true;
}
代码示例来源:origin: spring-projects/spring-framework
@Test
public void eventReaderSourceToDOMResult() throws Exception {
XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(XML));
StaxSource source = new StaxSource(eventReader);
assertEquals("Invalid eventReader returned", eventReader, source.getXMLEventReader());
assertNull("StreamReader returned", source.getXMLStreamReader());
Document expected = documentBuilder.parse(new InputSource(new StringReader(XML)));
Document result = documentBuilder.newDocument();
transformer.transform(source, new DOMResult(result));
assertThat("Invalid result", result, isSimilarTo(expected));
}
}
内容来源于网络,如有侵权,请联系作者删除!