/** * @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); }
@Test public final void testStAXSource2() throws XMLStreamException { XMLInputFactory ifactory = XMLInputFactory.newInstance(); ifactory.setProperty("javax.xml.stream.supportDTD", Boolean.TRUE); StAXSource ss = new StAXSource(ifactory.createXMLStreamReader(getClass().getResource("5368141.xml").toString(), getClass().getResourceAsStream("5368141.xml"))); DOMResult dr = new DOMResult(); TransformerFactory tfactory = TransformerFactory.newInstance(); try { Transformer transformer = tfactory.newTransformer(); transformer.transform(ss, dr); } catch (Exception e) { Assert.fail(e.getMessage()); } }
private void doTransform(String sXSL, OutputStream os) throws javax.xml.transform.TransformerConfigurationException, javax.xml.transform.TransformerException { // create the transformerfactory & transformer instance TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); if (null == sXSL) { t.transform(new DOMSource(doc), new StreamResult(os)); return; } try { Transformer finalTransformer = tf.newTransformer(new StreamSource(sXSL)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baos); t.transform(new DOMSource(doc), new StreamResult(bos)); bos.flush(); StreamSource xmlSource = new StreamSource(new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray()))); finalTransformer.transform(xmlSource, new StreamResult(os)); } catch (IOException ioe) { throw new javax.xml.transform.TransformerException(ioe); } }
/** * xml 格式化 * * @param xml * @return */ public static String xmlFormat(String xml) { if (TextUtils.isEmpty(xml)) { return "Empty/Null xml content"; } String message; 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); message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n"); } catch (TransformerException e) { message = xml; } return message; }
/** * 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 AlipayApiException 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; }
/** * Writes the modified web.xml back out to war file * * @param doc * The application.xml DOM Document * @throws org.apache.tools.ant.DeployException * in case of any problems */ protected void writeWebXml(final Document doc, final OutputStream outputStream) throws DeployException { try { doc.normalize(); // Prepare the DOM document for writing DOMSource source = new DOMSource(doc); // Prepare the output file StreamResult result = new StreamResult(outputStream); // Write the DOM document to the file // Get Transformer Transformer xformer = TransformerFactory.newInstance().newTransformer(); // Write to a file xformer.transform(source, result); } catch (TransformerException tex) { throw new DeployException("Error writing out modified web xml ", tex); } }
public static void write(Document doc, OutputStream out) throws IOException { // XXX note that this may fail to write out namespaces correctly if the document // is created with namespaces and no explicit prefixes; however no code in // this package is likely to be doing so try { Transformer t = TransformerFactory.newInstance().newTransformer( new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT))); DocumentType dt = doc.getDoctype(); if (dt != null) { String pub = dt.getPublicId(); if (pub != null) { t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub); } t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dt.getSystemId()); } t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N Source source = new DOMSource(doc); Result result = new StreamResult(out); t.transform(source, result); } catch (Exception | TransformerFactoryConfigurationError e) { throw new IOException(e); } }
public PomModifier(final Path projectDirectory, final Path gitDirectory) { if (builderFactory == null) { builderFactory = DocumentBuilderFactory.newInstance(); transformerFactory = TransformerFactory.newInstance(); try { builder = builderFactory.newDocumentBuilder(); transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); } catch (ParserConfigurationException | TransformerConfigurationException e) { throw new IllegalStateException(e); } } this.projectPomFile = gitDirectory.resolve("pom.xml"); this.projectDirectory = projectDirectory; this.gitDirectory = gitDirectory; }
/** * Test for the isIgnoringElementContentWhitespace and the * setIgnoringElementContentWhitespace. The xml file has all kinds of * whitespace,tab and newline characters, it uses the MyNSContentHandler * which does not invoke the characters callback when this * setIgnoringElementContentWhitespace is set to true. * @throws Exception If any errors occur. */ @Test public void testCheckElementContentWhitespace() throws Exception { String goldFile = GOLDEN_DIR + "dbfactory02GF.out"; String outputFile = USER_DIR + "dbfactory02.out"; MyErrorHandler eh = MyErrorHandler.newInstance(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(true); assertFalse(dbf.isIgnoringElementContentWhitespace()); dbf.setIgnoringElementContentWhitespace(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(eh); Document doc = db.parse(new File(XML_DIR, "DocumentBuilderFactory06.xml")); assertFalse(eh.isErrorOccured()); DOMSource domSource = new DOMSource(doc); TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer transformer = tfactory.newTransformer(); SAXResult saxResult = new SAXResult(); try(MyCHandler handler = MyCHandler.newInstance(new File(outputFile))) { saxResult.setHandler(handler); transformer.transform(domSource, saxResult); } assertTrue(compareWithGold(goldFile, outputFile)); }
public static String readMode(FileObject fo) throws IOException { final InputStream is = fo.getInputStream(); try { StringWriter w = new StringWriter(); Source t = new StreamSource(DesignSupport.class.getResourceAsStream("polishing.xsl")); // NOI18N Transformer tr = TransformerFactory.newInstance().newTransformer(t); Source s = new StreamSource(is); Result r = new StreamResult(w); tr.transform(s, r); return w.toString(); } catch (TransformerException ex) { throw new IOException(ex); } finally { is.close(); } }
/** * Builds a {@link VerificationResult} from a GeTeTa {@link Message}. * * @param source the original top-level XML node of the verification result * @param importedMessage the JAXB-converted GeTeTa {@link Message} object * @return the imported result * @throws ImportException if an error occurs while importing */ private VerificationResult makeVerificationResult(Node source, Message importedMessage) throws ImportException { try { /* Write log to file */ File logFile = File.createTempFile("log-verification-", ".xml"); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource domSource = new DOMSource(source); StreamResult result = new StreamResult(logFile); transformer.transform(domSource, result); /* Return appropriate VerificationResult */ switch (importedMessage.getReturncode()) { case RETURN_CODE_SUCCESS: return new VerificationSuccess(logFile); case RETURN_CODE_NOT_VERIFIED: return new edu.kit.iti.formal.stvs.model.verification.Counterexample( parseCounterexample(importedMessage), logFile); default: return new VerificationError(VerificationError.Reason.ERROR, logFile); } } catch (TransformerException | IOException exception) { throw new ImportException(exception); } }
private static String toString(Source response) throws TransformerException, IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(response, new StreamResult(bos)); bos.close(); return new String(bos.toByteArray()); }
/** * Transforms the XML content to XHTML/HTML format string with the XSL. * * @param payload the XML payload to convert * @param xsltFile the XML stylesheet file * @return the transformed XHTML/HTML format string * @throws AlipayApiException problem converting XML to HTML */ public static String xmlToHtml(String payload, File xsltFile) throws AlipayApiException { String result = null; try { Source template = new StreamSource(xsltFile); Transformer transformer = TransformerFactory.newInstance() .newTransformer(template); Properties props = transformer.getOutputProperties(); props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES); transformer.setOutputProperties(props); StreamSource source = new StreamSource(new StringReader(payload)); StreamResult sr = new StreamResult(new StringWriter()); transformer.transform(source, sr); result = sr.getWriter().toString(); } catch (TransformerException e) { throw new AlipayApiException("XML_TRANSFORM_ERROR", e); } return result; }
/** * Marshal the saml xml object to raw xml. * * @param object the object * @param writer the writer * @return the xml string */ public String marshalSamlXmlObject(final XMLObject object, final StringWriter writer) { try { final MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory(); final Marshaller marshaller = marshallerFactory.getMarshaller(object); if (marshaller == null) { throw new IllegalArgumentException("Cannot obtain marshaller for object " + object.getElementQName()); } final Element element = marshaller.marshall(object); element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", SAMLConstants.SAML20_NS); element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#"); final TransformerFactory transFactory = TransformerFactory.newInstance(); final Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(element), new StreamResult(writer)); return writer.toString(); } catch (final Exception e) { throw new IllegalStateException("An error has occurred while marshalling SAML object to xml", e); } }
protected String domSourceToString() throws SQLException { try { DOMSource source = new DOMSource(this.asDOMResult.getNode()); Transformer identity = TransformerFactory.newInstance().newTransformer(); StringWriter stringOut = new StringWriter(); Result result = new StreamResult(stringOut); identity.transform(source, result); return stringOut.toString(); } catch (Throwable t) { SQLException sqlEx = SQLError.createSQLException(t.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); sqlEx.initCause(t); throw sqlEx; } }
/** * 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; }
@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()); } }
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); } }
public static boolean saveFile(Document document, File file) { boolean flag = true; try { /** 将document中的内容写入文件中 */ TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); /** 编码 */ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(file); transformer.transform(source, result); } catch (Exception ex) { flag = false; ex.printStackTrace(); } return flag; }
/** * Transform saml object to String. * * @param configBean the config bean * @param samlObject the saml object * @return the string * @throws SamlException the saml exception */ public static StringWriter transformSamlObject(final OpenSamlConfigBean configBean, final XMLObject samlObject) throws SamlException { final StringWriter writer = new StringWriter(); try { final Marshaller marshaller = configBean.getMarshallerFactory().getMarshaller(samlObject.getElementQName()); if (marshaller != null) { final Element element = marshaller.marshall(samlObject); final DOMSource domSource = new DOMSource(element); final StreamResult result = new StreamResult(writer); final TransformerFactory tf = TransformerFactory.newInstance(); final Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); } } catch (final Exception e) { throw new SamlException(e.getMessage(), e); } return writer; }
@Override protected TransformerHandler getTransformerHandler(String xslFileName) throws SAXException, ParserConfigurationException, TransformerConfigurationException, IOException { SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance(); factory.setURIResolver(uriResolver); TemplatesHandler templatesHandler = factory.newTemplatesHandler(); SAXParserFactory pFactory = SAXParserFactory.newInstance(); pFactory.setNamespaceAware(true); XMLReader xmlreader = pFactory.newSAXParser().getXMLReader(); // create the stylesheet input source InputSource xslSrc = new InputSource(xslFileName); xslSrc.setSystemId(filenameToURL(xslFileName)); // hook up the templates handler as the xsl content handler xmlreader.setContentHandler(templatesHandler); // call parse on the xsl input source xmlreader.parse(xslSrc); // extract the Templates object created from the xsl input source return factory.newTransformerHandler(templatesHandler.getTemplates()); }
@Test public void test() { try { String xmlFile = "attribset27.xml"; String xslFile = "attribset27.xsl"; TransformerFactory tFactory = TransformerFactory.newInstance(); // tFactory.setAttribute("generate-translet", Boolean.TRUE); Transformer t = tFactory.newTransformer(new StreamSource(getClass().getResourceAsStream(xslFile))); StringWriter sw = new StringWriter(); t.transform(new StreamSource(getClass().getResourceAsStream(xmlFile)), new StreamResult(sw)); String s = sw.getBuffer().toString(); Assert.assertFalse(s.contains("color") || s.contains("font-size")); } catch (Exception e) { Assert.fail(e.getMessage()); } }
/** * Exports an Object as xml. * * @param source Object to export * @return The output xml is written to this stream * @throws ExportException Exception while exporting */ public ByteArrayOutputStream export(F source) throws ExportException { Node xmlNode = exportToXmlNode(source); StringWriter writer = new StringWriter(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(xmlNode), new StreamResult(writer)); String xmlString = writer.toString(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); stream.write(xmlString.getBytes("utf-8")); return stream; } catch (TransformerException | IOException e) { throw new ExportException(e); } }
private static void writeOut(Document doc) throws TransformerException { TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.STANDALONE, "no"); DOMSource source = new DOMSource(doc); File f = new File("splFile.xml"); f.delete(); StreamResult result = new StreamResult(f); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); }
public static String toString(Node node, boolean pretty) { if (pretty) { trimWhiteSpace(node); } DOMSource domSource = new DOMSource(node); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); try { Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); if (pretty) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } transformer.transform(domSource, result); return writer.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
@Test public void test() throws Exception { TransformerHandler th = ((SAXTransformerFactory) TransformerFactory.newInstance()).newTransformerHandler(); DOMResult result = new DOMResult(); th.setResult(result); th.startDocument(); th.startElement("", "root", "root", new AttributesImpl()); th.characters(new char[0], 0, 0); th.endElement("", "root", "root"); th.endDocument(); // there's no point in having empty text --- we should remove it Assert.assertEquals(0, ((Document) result.getNode()).getDocumentElement().getChildNodes().getLength()); }
@Test public void test() { try { Source source = new StreamSource(util.BOMInputStream.createStream("UTF-16BE", this.getClass().getResourceAsStream("Hello.wsdl.data")), this.getClass().getResource("Hello.wsdl.data").toExternalForm()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.transform(source, new StreamResult(baos)); System.out.println(new String(baos.toByteArray())); ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray()); InputSource inSource = new InputSource(bis); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE); XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(inSource.getSystemId(), inSource.getByteStream()); while (reader.hasNext()) { reader.next(); } } catch (Exception ex) { ex.printStackTrace(System.err); Assert.fail("Exception occured: " + ex.getMessage()); } }
/** * 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 save(String fileName) { try { // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); // Get (and preserve) Document's DOCTYPE attribute /// TODO: keving: String systemValue = (new File(((Document) getNode()).getDoctype().getSystemId())).getName(); // transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemValue); DOMSource source = new DOMSource((Document)getNode()); StreamResult result = new StreamResult(fileName); transformer.transform(source, result); } catch (Exception e) { logger.log(Level.INFO, "ERROR: Exception while saving XML document " + e.getMessage()); } }
private static void writeXml(final Document doc, final File file) throws IOException { doc.normalize(); final TransformerFactory transformerFactory = TransformerFactory.newInstance(XML_FACTORY, null); try { final Transformer transformer = transformerFactory.newTransformer(); 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(file)); } catch (final TransformerException ex) { throw new IOException(ex.getMessage(), ex); } }
/** * Hulpmethode om een xml fragment uit een node te halen middels xpath. * @param locatie de locatie van de node als xpath. * @param xPath een XPath instantie * @param node de basis node * @return de text */ protected static String getXmlFragment(final String locatie, final XPath xPath, final Node node) { try { final Node xPathNode = (Node) xPath.evaluate(locatie, node, XPathConstants.NODE); if (xPathNode != null) { final StringWriter buf = new StringWriter(); final Transformer xform = TransformerFactory.newInstance().newTransformer(); xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); xform.transform(new DOMSource(xPathNode), new StreamResult(buf)); return buf.toString(); } } catch (final XPathExpressionException | TransformerException e) { LOGGER.error("XPath voor text content kon niet worden geëvalueerd voor locatie {}.", locatie); throw new UnsupportedOperationException(e); } return null; }
/** * @bug 8152530 * Verifies that StAXSource handles empty namespace properly. NPE was thrown * before the fix. * @throws Exception if the test fails */ @Test public final void testStAXSourceWEmptyNS() throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<EntityList>\n" + " <Entity xmlns=\"\">\n" + " </Entity>\n" + " <Entity xmlns=\"\">\n" + " </Entity>\n" + "</EntityList> "; XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml)); xsr.nextTag(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT && xsr.getLocalName().equals("Entity")) { StringWriter stringResult = new StringWriter(); t.transform(new StAXSource(xsr), new StreamResult(stringResult)); System.out.println("result: \n" + stringResult.toString()); } }
/** * 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); } }
@Test public void test() { try { String xmlFile = "numbering63.xml"; String xslFile = "numbering63.xsl"; TransformerFactory tFactory = TransformerFactory.newInstance(); // tFactory.setAttribute("generate-translet", Boolean.TRUE); Transformer t = tFactory.newTransformer(new StreamSource(getClass().getResourceAsStream(xslFile), getClass().getResource(xslFile).toString())); StringWriter sw = new StringWriter(); t.transform(new StreamSource(getClass().getResourceAsStream(xmlFile)), new StreamResult(sw)); String s = sw.getBuffer().toString(); Assert.assertFalse(s.contains("1: Level A")); } catch (Exception e) { Assert.fail(e.getMessage()); } }
/** * Helper to make an XML Transformer. * * @param declaration If true, include the XML declaration. * @param indent If true, set up the transformer to indent. * @return A suitable {@code Transformer}. */ public static Transformer makeTransformer(boolean declaration, boolean indent) { Transformer tf = null; try { TransformerFactory factory = TransformerFactory.newInstance(); factory.setAttribute("indent-number", new Integer(2)); tf = factory.newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.METHOD, "xml"); if (!declaration) { tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } if (indent) { tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } } catch (TransformerException e) { logger.log(Level.WARNING, "Failed to install transformer!", e); } return tf; }