public static Document LoadXML(Source file) { try { DocumentBuilderFactory dbf = DocumentBuilderFactoryImpl.newInstance() ; DocumentBuilder db = dbf.newDocumentBuilder() ; Document doc = db.newDocument() ; Result res = new DOMResult(doc) ; TransformerFactory tr = TransformerFactory.newInstance(); Transformer xformer = tr.newTransformer(); xformer.transform(file, res); return doc ; } catch (Exception e) { String csError = e.toString(); Log.logImportant(csError); Log.logImportant("ERROR while loading XML "+file.toString()); } return null; }
public Document transformToDocument() { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); transformTo(new DOMResult(document)); return document; } catch (ParserConfigurationException ex) { throw new FluentXmlConfigurationException(ex); } }
public Document cloneDoc ( final Document doc ) throws TransformerException { final Transformer tx = this.tf.newTransformer (); final DOMSource source = new DOMSource ( doc ); final DOMResult result = new DOMResult (); tx.transform ( source, result ); return (Document)result.getNode (); }
/** * Retrieves a new Result for setting the XML value designated by this * SQLXML instance. * * @param resultClass The class of the result, or null. * @throws java.sql.SQLException if there is an error processing the XML * value or the state is not writable * @return for setting the XML value designated by this SQLXML instance. */ protected <T extends Result>T createResult( Class<T> resultClass) throws SQLException { checkWritable(); setWritable(false); setReadable(true); if (JAXBResult.class.isAssignableFrom(resultClass)) { // Must go first presently, since JAXBResult extends SAXResult // (purely as an implmentation detail) and it's not possible // to instantiate a valid JAXBResult with a Zero-Args // constructor(or any subclass thereof, due to the finality of // its private UnmarshallerHandler) // FALL THROUGH... will throw an exception } else if ((resultClass == null) || StreamResult.class.isAssignableFrom(resultClass)) { return createStreamResult(resultClass); } else if (DOMResult.class.isAssignableFrom(resultClass)) { return createDOMResult(resultClass); } else if (SAXResult.class.isAssignableFrom(resultClass)) { return createSAXResult(resultClass); } else if (StAXResult.class.isAssignableFrom(resultClass)) { return createStAXResult(resultClass); } throw JDBCUtil.invalidArgument("resultClass: " + resultClass); }
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. TransformerFactory tf = XmlUtil.newTransformerFactory(); Transformer t = tf.newTransformer(); XMLStreamBufferSource source = new XMLStreamBufferSource(_mark); DOMResult result = new DOMResult(); t.transform(source, result); Node d = result.getNode(); if(d.getNodeType() == Node.DOCUMENT_NODE) d = d.getFirstChild(); SOAPHeader header = saaj.getSOAPHeader(); if(header == null) header = saaj.getSOAPPart().getEnvelope().addHeader(); Node node = header.getOwnerDocument().importNode(d, true); header.appendChild(node); } catch (Exception e) { throw new SOAPException(e); } }
private Document createDOM(SDDocument doc) { // Get infoset ByteArrayBuffer bab = new ByteArrayBuffer(); try { doc.writeTo(null, resolver, bab); } catch (IOException ioe) { throw new WebServiceException(ioe); } // Convert infoset to DOM Transformer trans = XmlUtil.newTransformer(); Source source = new StreamSource(bab.newInputStream(), null); //doc.getURL().toExternalForm()); DOMResult result = new DOMResult(); try { trans.transform(source, result); } catch(TransformerException te) { throw new WebServiceException(te); } return (Document)result.getNode(); }
public DomSerializer(DOMResult domResult) { Node node = domResult.getNode(); if (node == null) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); domResult.setNode(doc); serializer = new SaxSerializer(new Dom2SaxAdapter(doc),null,false); } catch (ParserConfigurationException pce) { throw new TxwException(pce); } } else { serializer = new SaxSerializer(new Dom2SaxAdapter(node),null,false); } }
public Element getElement(DOMResult r) { // JAXP spec is ambiguous about what really happens in this case, // so work defensively Node n = r.getNode(); if( n instanceof Document ) { return ((Document)n).getDocumentElement(); } if( n instanceof Element ) return (Element)n; if( n instanceof DocumentFragment ) return (Element)n.getChildNodes().item(0); // if the result object contains something strange, // it is not a user problem, but it is a JAXB provider's problem. // That's why we throw a runtime exception. throw new IllegalStateException(n.toString()); }
public void setDOMResult(DOMResult result) { fCurrentNode = null; fFragmentRoot = null; fIgnoreChars = false; fTargetChildren.clear(); if (result != null) { fTarget = result.getNode(); fNextSibling = result.getNextSibling(); fDocument = (fTarget.getNodeType() == Node.DOCUMENT_NODE) ? (Document) fTarget : fTarget.getOwnerDocument(); fDocumentImpl = (fDocument instanceof CoreDocumentImpl) ? (CoreDocumentImpl) fDocument : null; fStorePSVI = (fDocument instanceof PSVIDocumentImpl); return; } fTarget = null; fNextSibling = null; fDocument = null; fDocumentImpl = null; fStorePSVI = false; }
public javax.xml.stream.XMLStreamWriter createXMLStreamWriter(javax.xml.transform.Result result) throws javax.xml.stream.XMLStreamException { if (result instanceof StreamResult) { return createXMLStreamWriter((StreamResult) result, null); } else if (result instanceof DOMResult) { return new XMLDOMWriterImpl((DOMResult) result); } else if (result instanceof StAXResult) { if (((StAXResult) result).getXMLStreamWriter() != null) { return ((StAXResult) result).getXMLStreamWriter(); } else { throw new java.lang.UnsupportedOperationException("Result of type " + result + " is not supported"); } } else { if (result.getSystemId() !=null) { //this is not correct impl of SAXResult. Keep it for now for compatibility return createXMLStreamWriter(new StreamResult(result.getSystemId())); } else { throw new java.lang.UnsupportedOperationException("Result of type " + result + " is not supported. " + "Supported result types are: DOMResult, StAXResult and StreamResult."); } } }
/** * Creates a new instance of XMLDOMwriterImpl * @param result DOMResult object @javax.xml.transform.dom.DOMResult */ public XMLDOMWriterImpl(DOMResult result) { node = result.getNode(); if( node.getNodeType() == Node.DOCUMENT_NODE){ ownerDoc = (Document)node; currentNode = ownerDoc; }else{ ownerDoc = node.getOwnerDocument(); currentNode = node; } getDLThreeMethods(); stringBuffer = new StringBuffer(); needContextPop = new boolean[resizeValue]; namespaceContext = new NamespaceSupport(); }
public static Document loadXML(ByteArrayInputStream byteArrayInputStream) { try { StreamSource streamSource = new StreamSource(byteArrayInputStream); DocumentBuilderFactory dbf = DocumentBuilderFactoryImpl.newInstance() ; DocumentBuilder db = dbf.newDocumentBuilder() ; Document doc = db.newDocument() ; Result res = new DOMResult(doc) ; TransformerFactory tr = TransformerFactory.newInstance(); Transformer xformer = tr.newTransformer(); xformer.transform(streamSource, res); return doc ; } catch (Exception e) { String csError = e.toString(); Log.logImportant(csError); Log.logImportant("ERROR while loading XML from byteArrayInputStream "+byteArrayInputStream.toString()); } return null; }
public boolean load(InputStream s) { try { Source file = new StreamSource(s) ; Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() ; Result res = new DOMResult(doc) ; TransformerFactory tr = TransformerFactory.newInstance(); Transformer xformer = tr.newTransformer(); xformer.transform(file, res); m_doc = doc; m_elem = m_doc.getDocumentElement(); return true; } catch (Exception e) { LogTagError.log(e); return false; } }
/** * Strips namespace information form the given node, to ease further processing. * I took the XSLT transformation from <a href= * "http://clardeur.blogspot.de/2012/11/remove-all-namespaces-from-xml-using.html">here</a>. * * @param node * The node. * @return A transformed node without namespace info. */ public static Node removeNamespaces(Node node) { Objects.requireNonNull(node, "node must not be null"); TransformerFactory transformerFactory = TransformerFactory.newInstance(); InputStream xslt = XmlUtils.class.getResourceAsStream(REMOVE_NAMESPACE_XSLT); if (xslt == null) { throw new IllegalStateException("Could not load " + REMOVE_NAMESPACE_XSLT + " -- InputStream == null"); } DOMResult result = new DOMResult(); try { Transformer transformer = transformerFactory.newTransformer(new StreamSource(xslt)); transformer.transform(new DOMSource(node), result); } catch (TransformerException e) { throw new IllegalStateException(e); } return result.getNode(); }
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. TransformerFactory tf = XmlUtil.newTransformerFactory(true); Transformer t = tf.newTransformer(); XMLStreamBufferSource source = new XMLStreamBufferSource(_mark); DOMResult result = new DOMResult(); t.transform(source, result); Node d = result.getNode(); if(d.getNodeType() == Node.DOCUMENT_NODE) d = d.getFirstChild(); SOAPHeader header = saaj.getSOAPHeader(); if(header == null) header = saaj.getSOAPPart().getEnvelope().addHeader(); Node node = header.getOwnerDocument().importNode(d, true); header.appendChild(node); } catch (Exception e) { throw new SOAPException(e); } }
/** * @bug 8139584 * Verifies that the resulting XML contains the standalone setting. */ @Test public void testCreateStartDocument_DOMWriter() throws ParserConfigurationException, XMLStreamException { XMLOutputFactory xof = XMLOutputFactory.newInstance(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); XMLEventWriter eventWriter = xof.createXMLEventWriter(new DOMResult(doc)); XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent event = eventFactory.createStartDocument("iso-8859-15", "1.0", true); eventWriter.add(event); eventWriter.flush(); Assert.assertEquals(doc.getXmlEncoding(), "iso-8859-15"); Assert.assertEquals(doc.getXmlVersion(), "1.0"); Assert.assertTrue(doc.getXmlStandalone()); }
private Source[] getSchemaSources() throws Exception { List<Source> list = new ArrayList<Source>(); String file = getClass().getResource("hello_literal.wsdl").getFile(); Source source = new StreamSource(new FileInputStream(file), file); Transformer trans = TransformerFactory.newInstance().newTransformer(); DOMResult result = new DOMResult(); trans.transform(source, result); // Look for <xsd:schema> element in wsdl Element e = ((Document) result.getNode()).getDocumentElement(); NodeList typesList = e.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "types"); NodeList schemaList = ((Element) typesList.item(0)).getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "schema"); Element elem = (Element) schemaList.item(0); list.add(new DOMSource(elem, file + "#schema0")); // trans.transform(new DOMSource(elem), new StreamResult(System.out)); return list.toArray(new Source[list.size()]); }
@Test public void test1() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); Document dom = parser.parse(Bug5072946.class.getResourceAsStream("Bug5072946.xml")); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema s = sf.newSchema(Bug5072946.class.getResource("Bug5072946.xsd")); Validator v = s.newValidator(); DOMResult r = new DOMResult(); // r.setNode(dbf.newDocumentBuilder().newDocument()); v.validate(new DOMSource(dom), r); Node node = r.getNode(); Assert.assertNotNull(node); Node fc = node.getFirstChild(); Assert.assertTrue(fc instanceof Element); Element e = (Element) fc; Assert.assertEquals("value", e.getAttribute("foo")); }
@Test public void test3() throws Exception { SAXTransformerFactory sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); Transformer t = sf.newTransformer(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); Document dom = parser.parse(Bug5072946.class.getResourceAsStream("Bug5072946.xml")); DOMResult r = new DOMResult(); t.transform(new DOMSource(dom), r); Assert.assertNotNull(r.getNode()); Node n = r.getNode().getFirstChild(); r.setNode(n); t.transform(new DOMSource(dom), r); Assert.assertNotNull(r.getNode()); Assert.assertSame(r.getNode(), n); r.setNextSibling(r.getNode().getFirstChild()); t.transform(new DOMSource(dom), r); Assert.assertNotNull(r.getNode()); Assert.assertSame(r.getNode(), n); }
@Test public void test() throws Exception { SAXParserFactory fac = SAXParserFactory.newInstance(); fac.setNamespaceAware(true); SAXParser saxParser = fac.newSAXParser(); StreamSource sr = new StreamSource(this.getClass().getResourceAsStream("SAX2DOMTest.xml")); InputSource is = SAXSource.sourceToInputSource(sr); RejectDoctypeSaxFilter rf = new RejectDoctypeSaxFilter(saxParser); SAXSource src = new SAXSource(rf, is); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMResult result = new DOMResult(); transformer.transform(src, result); Document doc = (Document) result.getNode(); System.out.println("Name" + doc.getDocumentElement().getLocalName()); String id = "XWSSGID-11605791027261938254268"; Element selement = doc.getElementById(id); if (selement == null) { System.out.println("getElementById returned null"); } }
@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()); } }
@Test public void run() throws Exception { // print input printSnippet("Source:", getSourceXml()); printSnippet("Stylesheet:", getXsl()); // transform to DOM result Transformer t = getTransformer(); DOMResult result = new DOMResult(); t.transform(getStreamSource(), result); // print output printSnippet("Result after transformation:", prettyPrintDOMResult(result)); // do some verifications Document document = (Document)result.getNode(); checkNodeNS(document.getElementsByTagName("test1").item(0), "ns2", "ns2", null); checkNodeNS(document.getElementsByTagName("test2").item(0), "ns1", "ns2", null); checkNodeNS(document.getElementsByTagName("test3").item(0), null, null, null); checkNodeNS(document.getElementsByTagName("test4").item(0), null, null, null); checkNodeNS(document.getElementsByTagName("test5").item(0), "ns1", "ns1", null); Assert.assertNull(document.getElementsByTagName("test6").item(0).getNamespaceURI(), "unexpected namespace for test6"); }
@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()); } }
@Test public final void test1() { try { long start = System.currentTimeMillis(); Transformer t = TransformerFactory.newInstance().newTransformer(); File file = new File(getClass().getResource("msgAttach.xml").getFile()); StreamSource source = new StreamSource(file); DOMResult result = new DOMResult(); t.transform(source, result); long end = System.currentTimeMillis(); System.out.println("Test2:Total Time Taken=" + (end - start)); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@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()); }
/** * Check grammar caching with imported schemas. * * @throws Exception If any errors occur. * @see <a href="content/coins.xsd">coins.xsd</a> * @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a> */ @Test public void testGetOwnerItemList() throws Exception { String xsdFile = XML_DIR + "coins.xsd"; String xmlFile = XML_DIR + "coins.xml"; try(FileInputStream fis = new FileInputStream(xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); dbf.setValidating(false); SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new File(((xsdFile)))); MyErrorHandler eh = new MyErrorHandler(); Validator validator = schema.newValidator(); validator.setErrorHandler(eh); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); Document document = docBuilder.parse(fis); validator.validate(new DOMSource(document), new DOMResult()); assertFalse(eh.isAnyError()); } }