Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); //initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); String xmlString = result.getWriter().toString(); System.out.println(xmlString);
public static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray()); } catch (Exception e) { return xml; } }
/** * Template method for handling {@code StreamResult}s. * <p>This implementation delegates to {@code marshalOutputStream} or {@code marshalWriter}, * depending on what is contained in the {@code StreamResult} * @param graph the root of the object graph to marshal * @param streamResult the {@code StreamResult} * @throws IOException if an I/O Exception occurs * @throws XmlMappingException if the given object cannot be marshalled to the result * @throws IllegalArgumentException if {@code streamResult} does neither * contain an {@code OutputStream} nor a {@code Writer} */ protected void marshalStreamResult(Object graph, StreamResult streamResult) throws XmlMappingException, IOException { if (streamResult.getOutputStream() != null) { marshalOutputStream(graph, streamResult.getOutputStream()); } else if (streamResult.getWriter() != null) { marshalWriter(graph, streamResult.getWriter()); } else { throw new IllegalArgumentException("StreamResult contains neither OutputStream nor Writer"); } }
private static String transform(Transformer transformer, Node element) throws TransformerException { StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(element); transformer.transform(source, result); return result.getWriter().toString(); }
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());
@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(); }
@Test public void namespacePrefixes() throws Exception { Assume.assumeTrue(wwwSpringframeworkOrgIsAccessible()); StringWriter stringWriter = new StringWriter(); AbstractStaxHandler handler = createStaxHandler(new StreamResult(stringWriter)); xmlReader.setContentHandler(handler); xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); xmlReader.setFeature("http://xml.org/sax/features/namespaces", true); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); xmlReader.parse(new InputSource(new StringReader(COMPLEX_XML))); assertThat(stringWriter.toString(), isSimilarTo(COMPLEX_XML).withNodeFilter(nodeFilter)); }
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 {
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); } }
argv[++i], ObjectFactory.findClassLoader(), true); tfactory.setURIResolver(uriResolver); DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); strResult = new StreamResult(new FileOutputStream(outFileName)); strResult.setSystemId(outFileName); strResult = new StreamResult(System.out); transformer.setErrorListener(new DefaultErrorHandler(false)); transformer.setOutputProperty(OutputKeys.METHOD, outputType); docBuilder.setEntityResolver(entityResolver); serializer.transform(new DOMSource(outNode), result); java.io.OutputStream out = strResult.getOutputStream(); java.io.Writer writer = strResult.getWriter(); try
@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)); }
@Test public void useAttributesForClassStringListMap() throws Exception { marshaller.setUseAttributeFor(Collections.singletonMap(Flight.class, Collections.singletonList("flightNumber"))); Writer writer = new StringWriter(); marshaller.marshal(flight, new StreamResult(writer)); String expected = "<flight flightNumber=\"42\" />"; assertThat("Marshaller does not use attributes", writer.toString(), isSimilarTo(expected)); }
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.newDocument(); if (null != sresult.getWriter()) serializer.setWriter(sresult.getWriter()); else if (null != sresult.getOutputStream()) serializer.setOutputStream(sresult.getOutputStream()); else if (null != sresult.getSystemId()) String fileURL = sresult.getSystemId();
((SAXSource)source).getInputSource()==null && ((SAXSource)source).getXMLReader()==null )|| (source instanceof DOMSource && ((DOMSource)source).getNode()==null)){ try { DocumentBuilderFactory builderF = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderF.newDocumentBuilder(); String systemID = source.getSystemId(); source = new DOMSource(builder.newDocument()); (SerializationHandler) SerializerFactory.getSerializer(format.getProperties()); if (null != sresult.getWriter()) serializer.setWriter(sresult.getWriter()); else if (null != sresult.getOutputStream()) serializer.setOutputStream(sresult.getOutputStream()); else if (null != sresult.getSystemId()) String fileURL = sresult.getSystemId();
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); } } }
/** * * @throws Exception */ @Test public void testGetEmployeeAsXml() throws Exception{ Map<String, Object> employeeSearchMap = getEmployeeSearchMap("0"); final String fullUrl = "http://localhost:8080/rest-http/services/employee/{id}/search"; EmployeeList employeeList = restTemplate.execute(fullUrl, HttpMethod.GET, new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest request) throws IOException { HttpHeaders headers = getHttpHeadersWithUserCredentials(request); headers.add("Accept", "application/xml"); } }, responseExtractor, employeeSearchMap); logger.info("The employee list size :"+employeeList.getEmployee().size()); StringWriter sw = new StringWriter(); StreamResult sr = new StreamResult(sw); marshaller.marshal(employeeList, sr); logger.info(sr.getWriter().toString()); assertTrue(employeeList.getEmployee().size() > 0); }
private String upgrade(String originalContent, URL upgradeScript) { try (InputStream xslt = upgradeScript.openStream()) { ByteArrayOutputStream convertedConfig = new ByteArrayOutputStream(); transformer(upgradeScript.getPath(), xslt) .transform(new StreamSource(new ByteArrayInputStream(originalContent.getBytes())), new StreamResult(convertedConfig)); return convertedConfig.toString(); } catch (TransformerException e) { throw bomb("Couldn't transform configuration file using upgrade script " + upgradeScript.getPath(), e); } catch (IOException e) { throw bomb("Couldn't write converted config file", e); } }
public static String saxonTransform(String source, String xslt) throws TransformerException, FileNotFoundException { TransformerFactoryImpl f = new net.sf.saxon.TransformerFactoryImpl(); f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE); StreamSource xsrc = new StreamSource(new FileInputStream(xslt)); Transformer t = f.newTransformer(xsrc); StreamSource src = new StreamSource(new FileInputStream(source)); StreamResult res = new StreamResult(new ByteArrayOutputStream()); t.transform(src, res); return res.getOutputStream().toString(); }
/** * Create the XSLT {@link Result} used to render the result of the transformation. * <p>The default implementation creates a {@link StreamResult} wrapping the supplied * HttpServletResponse's {@link HttpServletResponse#getOutputStream() OutputStream}. * @param response current HTTP response * @return the XSLT Result to use * @throws Exception if the Result cannot be built */ protected Result createResult(HttpServletResponse response) throws Exception { return new StreamResult(response.getOutputStream()); }
/** * Generate schema. */ public void doSchema(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { setHeaders(rsp); rsp.setContentType("application/xml"); StreamResult r = new StreamResult(rsp.getOutputStream()); new SchemaGenerator(new ModelBuilder().get(bean.getClass())).generateSchema(r); r.getOutputStream().close(); }