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());
/** * Template method for handling {@code DOMSource}s. * <p>This implementation delegates to {@code unmarshalDomNode}. * If the given source is empty, an empty source {@code Document} * will be created as a placeholder. * @param domSource the {@code DOMSource} * @return the object graph * @throws XmlMappingException if the given source cannot be mapped to an object * @throws IllegalArgumentException if the {@code domSource} is empty * @see #unmarshalDomNode(org.w3c.dom.Node) */ protected Object unmarshalDomSource(DOMSource domSource) throws XmlMappingException { if (domSource.getNode() == null) { domSource.setNode(buildDocument()); } try { return unmarshalDomNode(domSource.getNode()); } catch (NullPointerException ex) { if (!isSupportDtd()) { throw new UnmarshallingFailureException("NPE while unmarshalling. " + "This can happen on JDK 1.6 due to the presence of DTD " + "declarations, which are disabled.", ex); } throw ex; } }
private static String toString(org.w3c.dom.Node node) { try { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource domSource = new DOMSource(node); StringWriter out = new StringWriter(); transformer.transform(domSource, new StreamResult(out)); return out.toString(); } catch (TransformerException e) { throw new JSONException("xml node to string error", e); } }
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 {
@Test public void unmarshalDomSource() throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.newDocument(); Element flightsElement = document.createElementNS("http://samples.springframework.org/flight", "tns:flights"); document.appendChild(flightsElement); Element flightElement = document.createElementNS("http://samples.springframework.org/flight", "tns:flight"); flightsElement.appendChild(flightElement); Element numberElement = document.createElementNS("http://samples.springframework.org/flight", "tns:number"); flightElement.appendChild(numberElement); Text text = document.createTextNode("42"); numberElement.appendChild(text); DOMSource source = new DOMSource(document); Object flights = unmarshaller.unmarshal(source); testFlights(flights); }
private DOMSource readDOMSource(InputStream body, HttpInputMessage inputMessage) throws IOException { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setFeature( "http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); documentBuilderFactory.setFeature( DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); if (!isProcessExternalEntities()) { documentBuilder.setEntityResolver(NO_OP_ENTITY_RESOLVER); Document document = documentBuilder.parse(body); return new DOMSource(document);
private static Source mergeIntoSource(InputStream baseXmlStream, InputStream xmlStream) throws Exception { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setIgnoringComments(true); domFactory.setValidating(false); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document baseDoc = builder.parse(baseXmlStream); Document ruleDoc = builder.parse(xmlStream); // Shall this be more generic, i.e. reuse not just unification ??? NodeList unificationNodes = baseDoc.getElementsByTagName("unification"); Node ruleNode = ruleDoc.getElementsByTagName("rules").item(0); Node firstChildRuleNode = ruleNode.getChildNodes().item(1); for (int i = 0; i < unificationNodes.getLength(); i++) { Node unificationNode = ruleDoc.importNode(unificationNodes.item(i), true); ruleNode.insertBefore(unificationNode, firstChildRuleNode); } return new DOMSource(ruleDoc); }
// note that if your XML already declares the XSD to which it has to conform, then there's no need to declare the schemaName here void validate(String xml, String schemaName) throws Exception { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder parser = builderFactory .newDocumentBuilder(); // parse the XML into a document object Document document = parser.parse(new StringInputStream(xml)); SchemaFactory factory = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // associate the schema factory with the resource resolver, which is responsible for resolving the imported XSD's factory.setResourceResolver(new ResourceResolver()); // note that if your XML already declares the XSD to which it has to conform, then there's no need to create a validator from a Schema object Source schemaFile = new StreamSource(getClass().getClassLoader() .getResourceAsStream(schemaName)); Schema schema = factory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); }
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); } } }
/** * Emulate the Spring WS MessageDispatcherServlet by calling the gateway * with a DOMSource object representing the payload of the original SOAP * 'echoRequest' message. Expect an 'echoResponse' DOMSource object * to be returned in synchronous fashion, which the MessageDispatcherServlet * would in turn wrap in a SOAP envelope and return to the client. */ @Test public void testSendAndReceive() throws Exception { String xml = "<echoRequest xmlns=\"http://www.springframework.org/spring-ws/samples/echo\">hello</echoRequest>"; DomPoxMessageFactory messageFactory = new DomPoxMessageFactory(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(new InputSource(new StringReader(xml))); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DomPoxMessage request = new DomPoxMessage(document, transformer, "text/xml"); MessageContext messageContext = new DefaultMessageContext(request, messageFactory); gateway.invoke(messageContext); Object reply = messageContext.getResponse().getPayloadSource(); assertThat(reply, is(instanceOf(DOMSource.class))); DOMSource replySource = (DOMSource) reply; Element element = (Element) replySource.getNode().getFirstChild(); assertThat(element.getTagName(), equalTo("echoResponse")); } }
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; } }
@Override public DOMSource readFrom( Class<DOMSource> t, Type gt, Annotation[] as, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException { try { Document d = dbf.get().newDocumentBuilder().parse(entityStream); return new DOMSource(d); } catch (SAXParseException ex) { throw new BadRequestException(ex); } catch (SAXException ex) { throw new InternalServerErrorException(ex); } catch (ParserConfigurationException ex) { throw new InternalServerErrorException(ex); } } }
((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())
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); } }
/** * Parse the content as {@link DOMSource} and apply a {@link Matcher}. * @see <a href="https://github.com/davidehringer/xml-matchers">xml-matchers</a> */ public void assertSource(String content, Matcher<? super Source> matcher) throws Exception { Document document = parseXmlString(content); assertThat("Body content", new DOMSource(document), matcher); }
public Source issueResponseFor(DOMSource request) { return new DomSourceFactory().createSource( "<echoResponse xmlns=\"http://www.springframework.org/spring-ws/samples/echo\">" + request.getNode().getTextContent() + "</echoResponse>"); } }
node = dsource.getNode(); baseID = dsource.getSystemId();
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);
/** * Method createDocumentFragment * * * NEEDSDOC (createDocumentFragment) @return */ synchronized public DTM createDocumentFragment() { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); Node df = doc.createDocumentFragment(); return getDTM(new DOMSource(df), true, null, false, false); } catch (Exception e) { throw new DTMException(e); } }
private DOMSource readDOMSource(InputStream body, HttpInputMessage inputMessage) throws IOException { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setFeature( "http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); documentBuilderFactory.setFeature( DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); if (!isProcessExternalEntities()) { documentBuilder.setEntityResolver(NO_OP_ENTITY_RESOLVER); Document document = documentBuilder.parse(body); return new DOMSource(document);