下面列出了怎么用javax.xml.transform.TransformerFactory的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Transform based on parameters
*
* @param xmlIn XML
* @param xslIn XSL
* @param result Result
* @param paramMap Parameter map
* @throws javax.xml.transform.TransformerException
* will be thrown
*/
public static void transform(Source xmlIn, Source xslIn, Result result, Map paramMap)
throws TransformerException {
try {
TransformerFactory transformerFactory = new TransformerFactoryImpl();
Transformer transformer = transformerFactory.newTransformer(xslIn);
if (paramMap != null) {
Set set = paramMap.keySet();
for (Object aSet : set) {
if (aSet != null) {
String key = (String) aSet;
String value = (String) paramMap.get(key);
transformer.setParameter(key, value);
}
}
}
transformer.transform(xmlIn, result);
} catch (TransformerException e) {
log.error(e.getMessage(), e);
throw e;
}
}
private static String prettyFormatXML(String input) {
int indent = 5;
try {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", indent);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(xmlInput, xmlOutput);
return xmlOutput.getWriter().toString();
} catch (TransformerFactoryConfigurationError | IllegalArgumentException | TransformerException e) {
logger.log(Level.SEVERE, "Pretty print error", e);
return input;
}
}
public static void sample()throws Exception {
int no = 2;
String root = "EnterRoot";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.newDocument();
Element eRoot = d.createElement(root);
d.appendChild(eRoot);
for (int i = 1; i <= no; i++){
String element = "EnterElement";
String data = "Enter the data";
Element e = d.createElement(element);
e.appendChild(d.createTextNode(data));
eRoot.appendChild(e);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
DOMSource source = new DOMSource(d);
StreamResult result = new StreamResult(System.out);
t.transform(source, result);
}
/**
* 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();
}
@Test
public void test() {
try {
SAXParserFactory fac = SAXParserFactory.newInstance();
fac.setNamespaceAware(true);
SAXParser saxParser = fac.newSAXParser();
StreamSource src = new StreamSource(new StringReader(SIMPLE_TESTXML));
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
transformer.transform(src, result);
} catch (Throwable ex) {
// unexpected failure
ex.printStackTrace();
Assert.fail(ex.toString());
}
}
/**
*
* @param indent size of the indent (number of spaces)
* @return the formatted XML
*/
public String toFormattedString(@IntRange(from = 0) int indent) {
String input = toString();
try {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "" + indent);
transformer.transform(xmlInput, xmlOutput);
return xmlOutput.getWriter().toString();
} catch (Exception e) {
throw new RuntimeException(e); // TODO: do my own
}
}
private String transform(String xml, String xsl) {
try {
@SuppressWarnings("squid:S4435") // false positive
TransformerFactory tFactory = TransformerFactory.newInstance();
tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Source xslSource = new StreamSource(new ByteArrayInputStream(xsl.getBytes()));
Transformer transformer = tFactory.newTransformer(xslSource);
Source xmlSource = new StreamSource(new ByteArrayInputStream(xml.getBytes()));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
transformer.transform(xmlSource, new StreamResult(outputStream));
return new String(outputStream.toByteArray());
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Prints out the contents of the given xml, in a more readable form.
*
* @param bucketName the name of the bucket you're listing.
* @param content the raw XML string.
*/
private static void prettyPrintXml(final String bucketName, final String content) {
// Instantiate transformer input.
Source xmlInput = new StreamSource(new StringReader(content));
StreamResult xmlOutput = new StreamResult(new StringWriter());
// Configure transformer.
try {
Transformer transformer =
TransformerFactory.newInstance().newTransformer(); // An identity transformer
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
// Pretty print the output XML.
System.out.println("\nBucket listing for " + bucketName + ":\n");
System.out.println(xmlOutput.getWriter().toString());
} catch (TransformerException e) {
e.printStackTrace();
}
}
@Override
public ValidationResult validate(final String subject, final String input, final ValidationContext validationContext) {
final Tuple<String, ValidationResult> lastResult = this.cachedResult;
if (lastResult != null && lastResult.getKey().equals(input)) {
return lastResult.getValue();
} else {
String error = null;
final File stylesheet = new File(input);
final TransformerFactory tFactory = new net.sf.saxon.TransformerFactoryImpl();
final StreamSource styleSource = new StreamSource(stylesheet);
try {
tFactory.newTransformer(styleSource);
} catch (final Exception e) {
error = e.toString();
}
this.cachedResult = new Tuple<>(input, new ValidationResult.Builder()
.input(input)
.subject(subject)
.valid(error == null)
.explanation(error)
.build());
return this.cachedResult.getValue();
}
}
/**
* Test if two non nested xi:include elements can include the same document
* with an xi:include statement.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readWriteLocalFiles"})
public void testXIncludeNestedPos() throws Exception {
String resultFile = USER_DIR + "schedule.out";
String goldFile = GOLDEN_DIR + "scheduleGold.xml";
String xmlFile = XML_DIR + "schedule.xml";
try (FileOutputStream fos = new FileOutputStream(resultFile)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setXIncludeAware(true);
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile));
doc.setXmlStandalone(true);
TransformerFactory.newInstance().newTransformer()
.transform(new DOMSource(doc), new StreamResult(fos));
}
assertTrue(compareDocumentWithGold(goldFile, resultFile));
}
/**
* Write out the non-default properties in this configuration to the given
* {@link Writer}.
*
* @param out the writer to write to.
*/
public void writeXml(Writer out) throws IOException {
Document doc = asXmlDocument();
try {
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(out);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
// Important to not hold Configuration log while writing result, since
// 'out' may be an HDFS stream which needs to lock this configuration
// from another thread.
transformer.transform(source, result);
} catch (TransformerException te) {
throw new IOException(te);
}
}
/**
* Create a new XSLT transformer for the passed resource.
*
* @param aTransformerFactory
* The transformer factory to be used. May not be <code>null</code>.
* @param aSource
* The resource to be transformed. May not be <code>null</code>.
* @return <code>null</code> if something goes wrong
*/
@Nullable
public static Transformer newTransformer (@Nonnull final TransformerFactory aTransformerFactory,
@Nonnull final Source aSource)
{
ValueEnforcer.notNull (aTransformerFactory, "TransformerFactory");
ValueEnforcer.notNull (aSource, "Source");
try
{
return aTransformerFactory.newTransformer (aSource);
}
catch (final TransformerConfigurationException ex)
{
LOGGER.error ("Failed to parse " + aSource, ex);
return null;
}
}
/**
* Writes out this SerializableMetadata object in XML format to the
* OutputStream provided
*
* @param os
* The OutputStream this method writes to
* @throws IOException
* for any Exception
*/
public void writeMetadataToXmlStream(OutputStream os) throws IOException {
try {
// Prepare the DOM document for writing
Source source = new DOMSource(this.toXML());
Result result = new StreamResult(os);
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance()
.newTransformer();
xformer.setOutputProperty(OutputKeys.ENCODING, this.xmlEncoding);
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.transform(source, result);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
throw new IOException("Error generating metadata xml file!: "
+ e.getMessage());
}
}
/**
* @param destinationFolder Destination folder for saving the file
* @param fileName Destination file name
* @param doc Document object to be converted to xml formatted file
* @return Returns true if successfully converted
* @brief Converts a given Document object to xml format file
*/
public static boolean saveXmlFile(String destinationFolder, String fileName, Document doc) {
File f = new File(destinationFolder);
if (!f.isDirectory()) {
f.mkdirs();
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer;
try {
File newTemplateFile=new File(destinationFolder + fileName);
if(newTemplateFile.exists())
return false;
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(newTemplateFile);
transformer.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
}
return true;
}
/**
* the format should be something like this: [ ['My Workspace', null, ['Mary Morgan Folder', null, ['3 activity
* sequence','1024'] ], ['Organisations', null, ['Developers Playpen', null, ['Lesson Sequence Folder', null,
* ['',null] ] ], ['MATH111', null, ['Lesson Sequence Folder', null, ['',null] ] ] ] ] ]
*/
@Override
public String toString() {
// return '[' + convert() + ']';
Document document = getDocument();
try {
DOMSource domSource = new DOMSource(document);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
} catch (TransformerException ex) {
ex.printStackTrace();
return null;
}
}
public void CreateTaggedOutput()
{
try{
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(XMLDocumentTagged);
StreamResult result = new StreamResult(new File(filename));
transformer.transform(source, result);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
/**
* Test the simple case of including a document using xi:include within a
* xi:fallback using a DocumentBuilder.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readWriteLocalFiles"})
public void testXIncludeFallbackDOMPos() throws Exception {
String resultFile = USER_DIR + "doc_fallbackDOM.out";
String goldFile = GOLDEN_DIR + "doc_fallbackGold.xml";
String xmlFile = XML_DIR + "doc_fallback.xml";
try (FileOutputStream fos = new FileOutputStream(resultFile)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setXIncludeAware(true);
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile));
doc.setXmlStandalone(true);
TransformerFactory.newInstance().newTransformer()
.transform(new DOMSource(doc), new StreamResult(fos));
}
assertTrue(compareDocumentWithGold(goldFile, resultFile));
}
/**
* Write out the non-default properties in this configuration to the given
* {@link Writer}.
*
* @param out the writer to write to.
*/
public void writeXml(Writer out) throws IOException {
Document doc = asXmlDocument();
try {
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(out);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
// Important to not hold Configuration log while writing result, since
// 'out' may be an HDFS stream which needs to lock this configuration
// from another thread.
transformer.transform(source, result);
} catch (TransformerException te) {
throw new IOException(te);
}
}
/**
* Write out the non-default properties in this configuration to the given
* {@link Writer}.
*
* @param out the writer to write to.
*/
public void writeXml(Writer out) throws IOException {
Document doc = asXmlDocument();
try {
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(out);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
// Important to not hold Configuration log while writing result, since
// 'out' may be an HDFS stream which needs to lock this configuration
// from another thread.
transformer.transform(source, result);
} catch (TransformerException te) {
throw new IOException(te);
}
}
/**
* Converts the Node/Element instance to XML payload.
*
* @param node the node/element instance to convert
* @return the XML payload representing the node/element
* @throws ApiException problem converting XML to string
*/
public static String childNodeToString(Node node) throws AlipayApiException {
String payload = null;
try {
Transformer tf = TransformerFactory.newInstance().newTransformer();
Properties props = tf.getOutputProperties();
props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
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 AlipayApiException("XML_TRANSFORM_ERROR", e);
}
return payload;
}
private TransformerHandler getTransformerHandler() throws Exception {
SAXTransformerFactory tf = saxtf;
if (tf == null) {
saxtf = tf = (SAXTransformerFactory) TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
if (xsltFile == null) {
return tf.newTransformerHandler();
}
Templates tpls = xsltTpls;
if (tpls == null) {
xsltTpls = tpls = tf.newTemplates(new StreamSource(xsltFile));
}
return tf.newTransformerHandler(tpls);
}
public void createSolrSchema(List<ColumnNameTypeValue> columns, String confpath) throws ParserConfigurationException, URISyntaxException, IOException, SAXException, TransformerException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(new File(ClassLoader.getSystemResource("./solr-config/schema.xml").toURI()));
NodeList nodes = doc.getElementsByTagName("schema");
for (ColumnNameTypeValue column: columns) {
Element field = doc.createElement("field");
field.setAttribute("name", column.getColumn());
field.setAttribute("type", streamingToSolr(column.getType()));
field.setAttribute("indexed", "true");
field.setAttribute("stored", "true");
nodes.item(0).appendChild(field);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult streamResult = new StreamResult(new File(confpath+"/schema.xml"));
transformer.transform(source, streamResult);
}
@Test
public void main() throws Exception {
String carbonHome = System.getProperty(ConfigConstants.CARBON_HOME);
setAPIMConfigurations();
RegistryXmlConfigurator registryXmlConfigurator = new RegistryXmlConfigurator();
TransformerIdentityImpl transformerIdentity = PowerMockito.mock(TransformerIdentityImpl.class);
TransformerFactory transformerFactory = PowerMockito.mock(TransformerFactory.class);
PowerMockito.mockStatic(TransformerFactory.class);
PowerMockito.when(TransformerFactory.newInstance()).thenReturn(transformerFactory);
PowerMockito.when(transformerFactory.newTransformer()).thenReturn(transformerIdentity);
PowerMockito.doNothing().when(transformerIdentity).transform(any(DOMSource.class), any(StreamResult.class));
registryXmlConfigurator.configure(carbonConfigDirPath, gatewayConfigs);
Log4JConfigurator log4JConfigurator = new Log4JConfigurator();
log4JConfigurator.configure(carbonConfigDirPath);
Configurator.writeConfiguredLock(carbonHome);
//Cleaning the log4j.properties file
PrintWriter writer = new PrintWriter(carbonHome + File.separator + ConfigConstants.REPOSITORY_DIR + File.separator + ConfigConstants.CONF_DIR + File.separator + "log4j.properties");
writer.print("\n");
writer.close();
}
public static String asXmlString(Node node)
{
final Source source = new DOMSource(node);
final StringWriter stringWriter = new StringWriter();
final Result result = new StreamResult(stringWriter);
final TransformerFactory factory = TransformerFactory.newInstance();
try
{
final Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(source, result);
return stringWriter.getBuffer().toString();
}
catch (TransformerException exc)
{
throw new UncheckedIOException(exc.getMessage(), new IOException(exc));
}
}
public static String serializeXMLAsString(Element el, String xsltFileName) {
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
StringWriter sw = new StringWriter();
DOMSource source = new DOMSource(el);
ClassLoader cl = InternalDistributedSystem.class.getClassLoader();
// fix for bug 33274 - null classloader in Sybase app server
if (cl == null) {
cl = ClassLoader.getSystemClassLoader();
}
InputStream is = cl
.getResourceAsStream("com/pivotal/gemfirexd/internal/impl/tools/planexporter/resources/"
+ xsltFileName);
Transformer transformer = tFactory
.newTransformer(new javax.xml.transform.stream.StreamSource(is));
StreamResult result = new StreamResult(sw);
transformer.transform(source, result);
return sw.toString();
} catch (TransformerException te) {
throw GemFireXDRuntimeException.newRuntimeException(
"serializeXMLAsString: unexpected exception", te);
}
}
/**
* Returns properly configured (e.g. security features) factory
* - securityProcessing == is set based on security processing property, default is true
*/
public static TransformerFactory createTransformerFactory(boolean disableSecureProcessing) throws IllegalStateException {
try {
TransformerFactory factory = TransformerFactory.newInstance();
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "TransformerFactory instance: {0}", factory);
}
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing));
return factory;
} catch (TransformerConfigurationException ex) {
LOGGER.log(Level.SEVERE, null, ex);
throw new IllegalStateException( ex);
} catch (AbstractMethodError er) {
LOGGER.log(Level.SEVERE, null, er);
throw new IllegalStateException(Messages.INVALID_JAXP_IMPLEMENTATION.format(), er);
}
}
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);
}
}
/**
* 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");
}
}
public void init() throws ServletException {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
// Fortify Mod: prevent external entity injection
dbf.setExpandEntityReferences(false);
DB = dbf.newDocumentBuilder();
// Fortify Mod: prevent external entity injection
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
identityTransformer = tf.newTransformer();
// identityTransformer = TransformerFactory.newInstance().newTransformer();
// End Fortify Mod
servletName = this.getServletName();
} catch (Exception e) {
throw new ServletException(e);
}
}
public void saveToFile(File file) throws Exception{
Source domSource = new DOMSource(doc);
FileWriter writer = new FileWriter(file);
Result result = new StreamResult(writer);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(domSource, result);
writer.flush();writer.close();
}