下面列出了怎么用javax.xml.transform.Transformer的API类实例代码及写法,或者点击链接到github查看源代码。
public static Document loadDom(String url) {
Parser parser = new Parser();
try {
parser.setFeature(Parser.namespacesFeature, false);
parser.setFeature(Parser.namespacePrefixesFeature, false);
Reader reader = openReader(url);
DOMResult result = new DOMResult();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new SAXSource(parser, new InputSource(reader)), result);
reader.close();
return (Document) result.getNode();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static final void writeDoc(Document doc, OutputStream out)
throws IOException
{
try {
TransformerFactory tf = TransformerFactory.newInstance();
try {
tf.setAttribute("indent-number", new Integer(2));
} catch (IllegalArgumentException iae) {
}
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(new DOMSource(doc),
new StreamResult(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))));
} catch(TransformerException e) {
throw new AssertionError(e);
}
}
public static void testXmlClusteredCache(OsgiTestUtils.Cluster cluster) throws Exception {
File config = cluster.getWorkingArea().resolve("ehcache.xml").toFile();
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(TestMethods.class.getResourceAsStream("ehcache-clustered-osgi.xml"));
XPath xpath = XPathFactory.newInstance().newXPath();
Node clusterUriAttribute = (Node) xpath.evaluate("//config/service/cluster/connection/@url", doc, XPathConstants.NODE);
clusterUriAttribute.setTextContent(cluster.getConnectionUri().toString() + "/cache-manager");
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(doc), new StreamResult(config));
try (PersistentCacheManager cacheManager = (PersistentCacheManager) CacheManagerBuilder.newCacheManager(
new XmlConfiguration(config.toURI().toURL(), TestMethods.class.getClassLoader())
)) {
cacheManager.init();
final Cache<Long, Person> cache = cacheManager.getCache("clustered-cache", Long.class, Person.class);
cache.put(1L, new Person("Brian"));
assertThat(cache.get(1L).name, is("Brian"));
}
}
/**
* Create a Transformer object that from the input stylesheet
* Uses the com.sun.org.apache.xalan.internal.processor.TransformerFactory.
* @param source the stylesheet.
* @return A Transformer object.
*/
public Transformer newTransformer(Source source) throws
TransformerConfigurationException
{
if (_xalanFactory == null) {
createXalanTransformerFactory();
}
if (_errorlistener != null) {
_xalanFactory.setErrorListener(_errorlistener);
}
if (_uriresolver != null) {
_xalanFactory.setURIResolver(_uriresolver);
}
_currFactory = _xalanFactory;
return _currFactory.newTransformer(source);
}
protected void executeTemplate(String site, String path, OutputStream os) throws UpgradeException {
if(contentRepository.contentExists(site, path)) {
try(InputStream templateIs = template.getInputStream()) {
// Saxon is used to support XSLT 2.0
Transformer transformer =
TransformerFactory.newInstance(SAXON_CLASS, null)
.newTransformer(new StreamSource(templateIs));
logger.info("Applying XSLT template {0} to file {1} for site {2}", template, path, site);
try(InputStream sourceIs = contentRepository.getContent(site, path)) {
transformer.setParameter(PARAM_KEY_SITE, site);
transformer.setParameter(PARAM_KEY_VERSION, nextVersion);
transformer.setURIResolver(getURIResolver(site));
transformer.transform(new StreamSource(sourceIs), new StreamResult(os));
}
} catch (Exception e) {
throw new UpgradeException("Error processing file", e);
}
} else {
logger.warn("Source file {0} does not exist in site {1}", path, site);
}
}
private void removeByXpathExpression(String pomFilePath, String expression) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, TransformerException {
File xmlFile = new File(pomFilePath);
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList) xpath.compile(expression).
evaluate(doc, XPathConstants.NODESET);
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
node.getParentNode().removeChild(node);
}
Transformer transformer = TransformerFactory.newInstance().newTransformer();
// need to convert to file and then to path to override a problem with spaces
Result output = new StreamResult(new File(pomFilePath).getPath());
Source input = new DOMSource(doc);
transformer.transform(input, output);
}
}
/**
* @bug 8165116
* Verifies that redirect works properly when extension function is enabled
*
* @param xml the XML source
* @param xsl the stylesheet that redirect output to a file
* @param output the output file
* @param redirect the redirect file
* @throws Exception if the test fails
**/
@Test(dataProvider = "redirect")
public void testRedirect(String xml, String xsl, String output, String redirect) throws Exception {
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(ORACLE_ENABLE_EXTENSION_FUNCTION, true);
Transformer t = tf.newTransformer(new StreamSource(new StringReader(xsl)));
//Transform the xml
tryRunWithTmpPermission(
() -> t.transform(new StreamSource(new StringReader(xml)), new StreamResult(new StringWriter())),
new FilePermission(output, "write"), new FilePermission(redirect, "write"));
// Verifies that the output is redirected successfully
String userDir = getSystemProperty("user.dir");
Path pathOutput = Paths.get(userDir, output);
Path pathRedirect = Paths.get(userDir, redirect);
Assert.assertTrue(Files.exists(pathOutput));
Assert.assertTrue(Files.exists(pathRedirect));
System.out.println("Output to " + pathOutput + " successful.");
System.out.println("Redirect to " + pathRedirect + " successful.");
Files.deleteIfExists(pathOutput);
Files.deleteIfExists(pathRedirect);
}
/**
* Saves the search filters to the specified search filters file.
* @param filtersFile filters file to save to
*/
private void saveSearchFiltersFile( final File filtersFile ) {
try {
final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
final Element rootElement = document.createElement( "filters" );
rootElement.setAttribute( "version", "1.0" ); // To keep the possibility for future changes
for ( final SearchFieldGroup searchFieldGroup : searchFieldGroups )
searchFieldGroup.saveValues( document, rootElement );
document.appendChild( rootElement );
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
transformer.transform( new DOMSource( document ), new StreamResult( filtersFile ) );
GuiUtils.showInfoDialog( Language.getText( "module.repSearch.tab.filters.filtersSaved" ) );
} catch ( final Exception e ) {
e.printStackTrace();
GuiUtils.showErrorDialog( Language.getText( "module.repSearch.tab.filters.failedToSaveFilters" ) );
}
}
public void writeTo(SOAPMessage saaj) throws SOAPException {
try {
// TODO what about in-scope namespaces
// Not very efficient consider implementing a stream buffer
// processor that produces a DOM node from the buffer.
Transformer t = XmlUtil.newTransformer();
SOAPHeader header = saaj.getSOAPHeader();
if (header == null)
header = saaj.getSOAPPart().getEnvelope().addHeader();
// TODO workaround for oracle xdk bug 16555545, when this bug is fixed the line below can be
// uncommented and all lines below, except the catch block, can be removed.
// t.transform(epr.asSource(localName), new DOMResult(header));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(baos);
epr.writeTo(localName, w);
w.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
DocumentBuilderFactory fac = XmlUtil.newDocumentBuilderFactory(false);
fac.setNamespaceAware(true);
Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement();
Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true);
header.appendChild(eprNodeToAdd);
} catch (Exception e) {
throw new SOAPException(e);
}
}
/**
* @param xmlName
* the name of XML file
* @param stylesheetName
* the name of style sheet
* @param outputFile
* the name of log file
* @return boolean
* @see
* @since 1.0
*/
public boolean toStyledDocument(final String xmlName,
final String stylesheetName, final String outputFile) {
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslStream = new StreamSource(stylesheetName);
Transformer transformer;
try {
transformer = factory.newTransformer(xslStream);
StreamSource in = new StreamSource(xmlName);
StreamResult out = new StreamResult(outputFile);
transformer.transform(in, out);
} catch (TransformerException e) {
logger.debug(MessageCatalog._00101_TRANSFORMATION_EXCEPTION);
e.printStackTrace();
return false;
}
return true;
}
private void transform(EDLContext edlContext, Document dom, HttpServletResponse response) throws Exception {
if (StringUtils.isNotBlank(edlContext.getRedirectUrl())) {
response.sendRedirect(edlContext.getRedirectUrl());
return;
}
response.setContentType("text/html; charset=UTF-8");
Transformer transformer = edlContext.getTransformer();
transformer.setOutputProperty("indent", "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
String user = null;
String loggedInUser = null;
if (edlContext.getUserSession() != null) {
Person wu = edlContext.getUserSession().getPerson();
if (wu != null) user = wu.getPrincipalId();
wu = edlContext.getUserSession().getPerson();
if (wu != null) loggedInUser = wu.getPrincipalId();
}
transformer.setParameter("user", user);
transformer.setParameter("loggedInUser", loggedInUser);
if (LOG.isDebugEnabled()) {
LOG.debug("Transforming dom " + XmlJotter.jotNode(dom, true));
}
transformer.transform(new DOMSource(dom), new StreamResult(response.getOutputStream()));
}
private String copyDOMToString(Document wadlDoc) throws Exception {
DOMSource domSource = new DOMSource(wadlDoc);
// temporary workaround
StringWriter stringWriter = new StringWriter();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
try {
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
} catch (IllegalArgumentException ex) {
// ignore
}
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(domSource, new StreamResult(stringWriter));
return stringWriter.toString();
}
/** Transform an xsl-fo StreamSource to the specified output format.
* @param src The xsl-fo StreamSource instance
* @param stylesheet Optional stylesheet StreamSource instance
* @param fop
*/
public static void transform(StreamSource src, StreamSource stylesheet, Fop fop) throws FOPException {
Result res = new SAXResult(fop.getDefaultHandler());
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer;
if (stylesheet == null) {
transformer = factory.newTransformer();
} else {
transformer = factory.newTransformer(stylesheet);
}
transformer.setURIResolver(new LocalResolver(transformer.getURIResolver()));
transformer.transform(src, res);
} catch (Exception e) {
throw new FOPException(e);
}
}
public Source invoke(Source request) {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try {
transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
/*
tfactory.setAttribute("indent-number", "2");
*/
Transformer serializer = transformerFactory.newTransformer();
// Setup indenting to "pretty print"
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StringWriter swriter = new StringWriter();
serializer.transform(request, new StreamResult(swriter));
swriter.flush();
LOG.info("Provider received a request\n" + swriter.toString());
} catch (TransformerException e) {
e.printStackTrace();
}
return null;
}
/**
* Pretty print XML Node
* @param node
* @return
* @throws XmlUtilitiesException
*/
public String xmlNodeToString( Node node ) throws XmlUtilitiesException {
StringWriter sw = new StringWriter();
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4");
transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_LINE_SEPARATOR, "\n");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException te) {
throw new XmlUtilitiesException("Error transforming XML node to String", te);
}
return sw.toString().trim();
}
private String writeDocument(Document d) {
try {
DOMSource source = new DOMSource(d);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
return writer.toString();
}
catch (Exception e) {
return null;
}
}
/**
* Adds the specified element to the XML document and returns the document's contents as a String
*/
public static String addElementAndGetDocumentAsString(Document doc, Element el)
{
doc.appendChild(el);
try {
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
Source src = new DOMSource(doc);
StringWriter writer = new StringWriter();
Result dest = new StreamResult(writer);
aTransformer.transform(src, dest);
String result = writer.getBuffer().toString();
return result;
}
catch (Exception e) {
throw new ContentReviewProviderException("Failed to transform the XML Document into a String");
}
}
private void buildSubsystemXml(final Element element, final String expression) throws IOException {
if (element != null) {
try {
// locate the element and insert the node
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(this.document, XPathConstants.NODESET);
nodeList.item(0).appendChild(element);
// transform again to XML
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(this.document), new StreamResult(writer));
this.subsystemXml = writer.getBuffer().toString();
} catch(TransformerException | XPathExpressionException e) {
throw new IOException(e);
}
} else {
this.subsystemXml = this.subsystemTemplate;
}
}
/**
* 更新配置信息
*
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
* @throws TransformerException
*/
@Override
public void updateFileLimit(long fileSize, long allfileSize,
String allowType, String bannedType,String path)
throws ParserConfigurationException, SAXException, IOException,
TransformerException {
Document document = HandleXMLFileDaoImpl.getDocument(path);
Element element = document.getDocumentElement();
NodeList nodes = element.getElementsByTagName("limit");
// Element limitElement = (Element)nodes.item(0);
for (int i = 0; i < nodes.getLength(); i++) { // 可不用循环
Element limitElement = (Element) nodes.item(i);
NodeList childNodes = limitElement.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node node = childNodes.item(j);
if (node.getNodeType() == Node.ELEMENT_NODE) {
if ("fileSize".equals(node.getNodeName())) { // 上传文件大小
node.getFirstChild().setTextContent(fileSize+"");
} else if ("allfileSize".equals(node.getNodeName())) { // 所有文件大小
node.getFirstChild().setTextContent(allfileSize+"");
} else if ("allowType".equals(node.getNodeName())) { // 允许上传类型
node.getFirstChild().setTextContent(allowType);
} else if ("bannedType".equals(node.getNodeName())) { // 禁止上传类型
node.getFirstChild().setTextContent(bannedType);
}
}
}
}
// 重新解析为xml文件
TransformerFactory tf = TransformerFactory.newInstance();
Transformer tfer = tf.newTransformer();
DOMSource dsource = new DOMSource(document);
File file = new File(path);
FileOutputStream out = new FileOutputStream(file);
out.flush();
StreamResult sr = new StreamResult(out);
tfer.transform(dsource, sr);
out.close();
}
private static Transformer getTransformer(String stylesheet) throws IOException, TransformerConfigurationException {
try (InputStream in = XSLTransformation.class.getResourceAsStream(stylesheet);
InputStream xslStream = new BufferedInputStream(in)) {
StreamSource src = new StreamSource(xslStream);
src.setSystemId(stylesheet);
return TransformerFactory.newInstance().newTransformer(src);
}
}
/**
* Converts DOM object to String. This is a helper method for creating cache key
*
* @param node Node value
* @return String Object
* @throws javax.xml.transform.TransformerException Exception throws if fails
*/
private String domToString(Node node) throws TransformerException {
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node),
new StreamResult(buffer));
return buffer.toString();
}
public static void main(String[] args) throws TransformerException {
ByteArrayOutputStream resStream = new ByteArrayOutputStream();
TransformerFactory trf = TransformerFactory.newInstance();
Transformer tr = trf.newTransformer(new StreamSource(System.getProperty("test.src", ".") + XSLTRANSFORMER));
tr.transform(new StreamSource(System.getProperty("test.src", ".") + XMLTOTRANSFORM), new StreamResult(resStream));
System.out.println("Transformation completed. Result:" + resStream.toString());
if (!resStream.toString().equals(EXPECTEDRESULT)) {
throw new RuntimeException("Incorrect transformation result");
}
}
public static void saveDoc(Document doc, String fileName)
{
try
{
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(fileName));
transformer.transform(source, result);
} catch (TransformerException e)
{
e.printStackTrace();
}
}
/**
* Enable indenting for the supplied {@link javax.xml.transform.Transformer}.
* <p>If the underlying XSLT engine is Xalan, then the special output key {@code indent-amount}
* will be also be set to a value of {@link #DEFAULT_INDENT_AMOUNT} characters.
* @param transformer the target transformer
* @param indentAmount the size of the indent (2 characters, 3 characters, etc)
* @see javax.xml.transform.Transformer#setOutputProperty(String, String)
* @see javax.xml.transform.OutputKeys#INDENT
*/
public static void enableIndenting(Transformer transformer, int indentAmount) {
Assert.notNull(transformer, "Transformer must not be null");
if (indentAmount < 0) {
throw new IllegalArgumentException("Invalid indent amount (must not be less than zero): " + indentAmount);
}
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
try {
// Xalan-specific, but this is the most common XSLT engine in any case
transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", String.valueOf(indentAmount));
}
catch (IllegalArgumentException ignored) {
}
}
@Override
public boolean init( ) {
if ( !super.init() ) {
return false;
}
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
if ( meta.getEncoding() != null ) {
transformer.setOutputProperty( OutputKeys.ENCODING, meta.getEncoding() );
}
if ( meta.isOmitXmlHeader() ) {
transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
}
transformer.setOutputProperty( OutputKeys.INDENT, "no" );
setTransformer( transformer );
// See if a main step is supplied: in that case move the corresponding rowset to position 0
//
swapFirstInputRowSetIfExists( meta.getTargetXmlStep() );
} catch ( Exception e ) {
log.logError( BaseMessages.getString( PKG, "XMLJoin.Error.Init" ), e );
return false;
}
return true;
}
private void writeDocumentAsFile(Document doc, String fileName) throws TransformerFactoryConfigurationError, TransformerException {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(new File("output.xml"));
Source input = new DOMSource(doc);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(input, output);
}
private void setOutputFormat(Transformer transformer) {
Properties outFormat = new Properties();
outFormat.setProperty(INDENT, "yes");
outFormat.setProperty(METHOD, "xml");
outFormat.setProperty(OMIT_XML_DECLARATION, "no");
outFormat.setProperty(VERSION, "1.0");
outFormat.setProperty(ENCODING, UTF_8);
transformer.setOutputProperties(outFormat);
}
public Document xmlResource( String resource ) throws TransformerException, IOException
{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
URL url = resource( resource );
transformer.transform( new StreamSource( url.openStream(), url.toString() ), result );
return (Document) result.getNode();
}
/**
* Write a {@link Document} to a {@link Writer}.
*
* @param doc the document to write
* @param output the output, where the document is written to
* @param prettyPrint if pretty printing is enabled for the generated XML code
* @throws TransformerException if XML transformation failed
*/
public static void write(Document doc, Writer output, boolean prettyPrint) throws TransformerException {
XmlUtils.clean(doc);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, (prettyPrint) ? "yes" : "no");
if (prettyPrint) {
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
}
transformer.transform(new DOMSource(doc), new StreamResult(output));
}
/**
* javax.xml.transform.sax.SAXTransformerFactory implementation.
* Get a TransformerHandler object that can process SAX ContentHandler
* events into a Result, based on the transformation instructions
* specified by the argument.
*
* @param src The source of the transformation instructions.
* @return A TransformerHandler object that can handle SAX events
* @throws TransformerConfigurationException
*/
@Override
public TransformerHandler newTransformerHandler(Source src)
throws TransformerConfigurationException
{
final Transformer transformer = newTransformer(src);
if (_uriResolver != null) {
transformer.setURIResolver(_uriResolver);
}
return new TransformerHandlerImpl((TransformerImpl) transformer);
}