List of usage examples for org.w3c.dom Document createDocumentFragment
public DocumentFragment createDocumentFragment();
DocumentFragment
object. From source file:org.apache.ode.jbi.EndpointReferenceContextImpl.java
public EndpointReference convertEndpoint(QName eprType, Element epr) { Document doc = DOMUtils.newDocument(); DocumentFragment fragment = doc.createDocumentFragment(); NodeList children = epr.getChildNodes(); for (int i = 0; i < children.getLength(); ++i) fragment.appendChild(doc.importNode(children.item(i), true)); ServiceEndpoint se = _ode.getContext().resolveEndpointReference(fragment); if (se == null) return null; return new JbiEndpointReference(se, eprType); }
From source file:org.apache.ode.utils.DOMUtils.java
/** * Deep clone, but don't fry, the given node in the context of the given document. * For all intents and purposes, the clone is the exact same copy of the node, * except that it might have a different owner document. * * This method is fool-proof, unlike the <code>adoptNode</code> or <code>adoptNode</code> methods, * in that it doesn't assume that the given node has a parent or a owner document. * * @param document// w w w . j a v a2s . c o m * @param sourceNode * @return a clone of node */ public static Node cloneNode(Document document, Node sourceNode) { Node clonedNode = null; // what is my name? QName sourceQName = getNodeQName(sourceNode); String nodeName = sourceQName.getLocalPart(); String namespaceURI = sourceQName.getNamespaceURI(); // if the node is unqualified, don't assume that it inherits the WS-BPEL target namespace if (Namespaces.WSBPEL2_0_FINAL_EXEC.equals(namespaceURI)) { namespaceURI = null; } switch (sourceNode.getNodeType()) { case Node.ATTRIBUTE_NODE: if (namespaceURI == null) { clonedNode = document.createAttribute(nodeName); } else { String prefix = ((Attr) sourceNode).lookupPrefix(namespaceURI); // the prefix for the XML namespace can't be looked up, hence this... if (prefix == null && namespaceURI.equals(NS_URI_XMLNS)) { prefix = "xmlns"; } // if a prefix exists, qualify the name with it if (prefix != null && !"".equals(prefix)) { nodeName = prefix + ":" + nodeName; } // create the appropriate type of attribute if (prefix != null) { clonedNode = document.createAttributeNS(namespaceURI, nodeName); } else { clonedNode = document.createAttribute(nodeName); } } break; case Node.CDATA_SECTION_NODE: clonedNode = document.createCDATASection(((CDATASection) sourceNode).getData()); break; case Node.COMMENT_NODE: clonedNode = document.createComment(((Comment) sourceNode).getData()); break; case Node.DOCUMENT_FRAGMENT_NODE: clonedNode = document.createDocumentFragment(); break; case Node.DOCUMENT_NODE: clonedNode = document; break; case Node.ELEMENT_NODE: // create the appropriate type of element if (namespaceURI == null) { clonedNode = document.createElement(nodeName); } else { String prefix = namespaceURI.equals(Namespaces.XMLNS_URI) ? "xmlns" : ((Element) sourceNode).lookupPrefix(namespaceURI); if (prefix != null && !"".equals(prefix)) { nodeName = prefix + ":" + nodeName; clonedNode = document.createElementNS(namespaceURI, nodeName); } else { clonedNode = document.createElement(nodeName); } } // attributes are not treated as child nodes, so copy them explicitly NamedNodeMap attributes = ((Element) sourceNode).getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Attr attributeClone = (Attr) cloneNode(document, attributes.item(i)); if (attributeClone.getNamespaceURI() == null) { ((Element) clonedNode).setAttributeNode(attributeClone); } else { ((Element) clonedNode).setAttributeNodeNS(attributeClone); } } break; case Node.ENTITY_NODE: // TODO break; case Node.ENTITY_REFERENCE_NODE: clonedNode = document.createEntityReference(nodeName); // TODO break; case Node.NOTATION_NODE: // TODO break; case Node.PROCESSING_INSTRUCTION_NODE: clonedNode = document.createProcessingInstruction(((ProcessingInstruction) sourceNode).getData(), nodeName); break; case Node.TEXT_NODE: clonedNode = document.createTextNode(((Text) sourceNode).getData()); break; default: break; } // clone children of element and attribute nodes NodeList sourceChildren = sourceNode.getChildNodes(); if (sourceChildren != null) { for (int i = 0; i < sourceChildren.getLength(); i++) { Node sourceChild = sourceChildren.item(i); Node clonedChild = cloneNode(document, sourceChild); clonedNode.appendChild(clonedChild); // if the child has a textual value, parse it for any embedded prefixes if (clonedChild.getNodeType() == Node.TEXT_NODE || clonedChild.getNodeType() == Node.CDATA_SECTION_NODE) { parseEmbeddedPrefixes(sourceNode, clonedNode, clonedChild); } } } return clonedNode; }
From source file:org.apache.servicemix.jbi.deployer.descriptor.DescriptorFactory.java
/** * Build a jbi descriptor from the specified binary data. * The descriptor is validated against the schema, but no * semantic validation is performed./*from w w w .j ava2 s . co m*/ * * @param bytes hold the content of the JBI descriptor xml document * @return the Descriptor object */ public static Descriptor buildDescriptor(final byte[] bytes) { try { // Validate descriptor SchemaFactory schemaFactory = SchemaFactory.newInstance(XSD_SCHEMA_LANGUAGE); Schema schema = schemaFactory.newSchema(DescriptorFactory.class.getResource(JBI_DESCRIPTOR_XSD)); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { //log.debug("Validation warning on " + url + ": " + exception); } public void error(SAXParseException exception) throws SAXException { //log.info("Validation error on " + url + ": " + exception); } public void fatalError(SAXParseException exception) throws SAXException { throw exception; } }); validator.validate(new StreamSource(new ByteArrayInputStream(bytes))); // Parse descriptor DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.parse(new ByteArrayInputStream(bytes)); Element jbi = doc.getDocumentElement(); Descriptor desc = new Descriptor(); desc.setVersion(Double.parseDouble(getAttribute(jbi, VERSION))); Element child = getFirstChildElement(jbi); if (COMPONENT.equals(child.getLocalName())) { ComponentDesc component = new ComponentDesc(); component.setType(child.getAttribute(TYPE)); component.setComponentClassLoaderDelegation(getAttribute(child, COMPONENT_CLASS_LOADER_DELEGATION)); component.setBootstrapClassLoaderDelegation(getAttribute(child, BOOTSTRAP_CLASS_LOADER_DELEGATION)); List<SharedLibraryList> sls = new ArrayList<SharedLibraryList>(); DocumentFragment ext = null; for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (IDENTIFICATION.equals(e.getLocalName())) { component.setIdentification(readIdentification(e)); } else if (COMPONENT_CLASS_NAME.equals(e.getLocalName())) { component.setComponentClassName(getText(e)); component.setDescription(getAttribute(e, DESCRIPTION)); } else if (COMPONENT_CLASS_PATH.equals(e.getLocalName())) { ClassPath componentClassPath = new ClassPath(); ArrayList<String> l = new ArrayList<String>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (PATH_ELEMENT.equals(e2.getLocalName())) { l.add(getText(e2)); } } componentClassPath.setPathList(l); component.setComponentClassPath(componentClassPath); } else if (BOOTSTRAP_CLASS_NAME.equals(e.getLocalName())) { component.setBootstrapClassName(getText(e)); } else if (BOOTSTRAP_CLASS_PATH.equals(e.getLocalName())) { ClassPath bootstrapClassPath = new ClassPath(); ArrayList<String> l = new ArrayList<String>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (PATH_ELEMENT.equals(e2.getLocalName())) { l.add(getText(e2)); } } bootstrapClassPath.setPathList(l); component.setBootstrapClassPath(bootstrapClassPath); } else if (SHARED_LIBRARY.equals(e.getLocalName())) { SharedLibraryList sl = new SharedLibraryList(); sl.setName(getText(e)); sl.setVersion(getAttribute(e, VERSION)); sls.add(sl); } else { if (ext == null) { ext = doc.createDocumentFragment(); } ext.appendChild(e); } } component.setSharedLibraries(sls.toArray(new SharedLibraryList[sls.size()])); if (ext != null) { InstallationDescriptorExtension descriptorExtension = new InstallationDescriptorExtension(); descriptorExtension.setDescriptorExtension(ext); component.setDescriptorExtension(descriptorExtension); } desc.setComponent(component); } else if (SHARED_LIBRARY.equals(child.getLocalName())) { SharedLibraryDesc sharedLibrary = new SharedLibraryDesc(); sharedLibrary.setClassLoaderDelegation(getAttribute(child, CLASS_LOADER_DELEGATION)); sharedLibrary.setVersion(getAttribute(child, VERSION)); for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (IDENTIFICATION.equals(e.getLocalName())) { sharedLibrary.setIdentification(readIdentification(e)); } else if (SHARED_LIBRARY_CLASS_PATH.equals(e.getLocalName())) { ClassPath sharedLibraryClassPath = new ClassPath(); ArrayList<String> l = new ArrayList<String>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (PATH_ELEMENT.equals(e2.getLocalName())) { l.add(getText(e2)); } } sharedLibraryClassPath.setPathList(l); sharedLibrary.setSharedLibraryClassPath(sharedLibraryClassPath); } } desc.setSharedLibrary(sharedLibrary); } else if (SERVICE_ASSEMBLY.equals(child.getLocalName())) { ServiceAssemblyDesc serviceAssembly = new ServiceAssemblyDesc(); ArrayList<ServiceUnitDesc> sus = new ArrayList<ServiceUnitDesc>(); for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (IDENTIFICATION.equals(e.getLocalName())) { serviceAssembly.setIdentification(readIdentification(e)); } else if (SERVICE_UNIT.equals(e.getLocalName())) { ServiceUnitDesc su = new ServiceUnitDesc(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (IDENTIFICATION.equals(e2.getLocalName())) { su.setIdentification(readIdentification(e2)); } else if (TARGET.equals(e2.getLocalName())) { Target target = new Target(); for (Element e3 = getFirstChildElement(e2); e3 != null; e3 = getNextSiblingElement( e3)) { if (ARTIFACTS_ZIP.equals(e3.getLocalName())) { target.setArtifactsZip(getText(e3)); } else if (COMPONENT_NAME.equals(e3.getLocalName())) { target.setComponentName(getText(e3)); } } su.setTarget(target); } } sus.add(su); } else if (CONNECTIONS.equals(e.getLocalName())) { Connections connections = new Connections(); ArrayList<Connection> cns = new ArrayList<Connection>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (CONNECTION.equals(e2.getLocalName())) { Connection cn = new Connection(); for (Element e3 = getFirstChildElement(e2); e3 != null; e3 = getNextSiblingElement( e3)) { if (CONSUMER.equals(e3.getLocalName())) { Consumer consumer = new Consumer(); consumer.setInterfaceName(readAttributeQName(e3, INTERFACE_NAME)); consumer.setServiceName(readAttributeQName(e3, SERVICE_NAME)); consumer.setEndpointName(getAttribute(e3, ENDPOINT_NAME)); cn.setConsumer(consumer); } else if (PROVIDER.equals(e3.getLocalName())) { Provider provider = new Provider(); provider.setServiceName(readAttributeQName(e3, SERVICE_NAME)); provider.setEndpointName(getAttribute(e3, ENDPOINT_NAME)); cn.setProvider(provider); } } cns.add(cn); } } connections.setConnections(cns.toArray(new Connection[cns.size()])); serviceAssembly.setConnections(connections); } } serviceAssembly.setServiceUnits(sus.toArray(new ServiceUnitDesc[sus.size()])); desc.setServiceAssembly(serviceAssembly); } else if (SERVICES.equals(child.getLocalName())) { Services services = new Services(); services.setBindingComponent( Boolean.valueOf(getAttribute(child, BINDING_COMPONENT)).booleanValue()); ArrayList<Provides> provides = new ArrayList<Provides>(); ArrayList<Consumes> consumes = new ArrayList<Consumes>(); for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (PROVIDES.equals(e.getLocalName())) { Provides p = new Provides(); p.setInterfaceName(readAttributeQName(e, INTERFACE_NAME)); p.setServiceName(readAttributeQName(e, SERVICE_NAME)); p.setEndpointName(getAttribute(e, ENDPOINT_NAME)); provides.add(p); } else if (CONSUMES.equals(e.getLocalName())) { Consumes c = new Consumes(); c.setInterfaceName(readAttributeQName(e, INTERFACE_NAME)); c.setServiceName(readAttributeQName(e, SERVICE_NAME)); c.setEndpointName(getAttribute(e, ENDPOINT_NAME)); c.setLinkType(getAttribute(e, LINK_TYPE)); consumes.add(c); } } services.setProvides(provides.toArray(new Provides[provides.size()])); services.setConsumes(consumes.toArray(new Consumes[consumes.size()])); desc.setServices(services); } checkDescriptor(desc); return desc; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.servicemix.jbi.runtime.impl.ServiceEndpointImpl.java
public DocumentFragment getAsReference(QName operationName) { try {//from ww w .ja va2 s. co m Document doc = DOMUtil.newDocument(); DocumentFragment fragment = doc.createDocumentFragment(); Element epr = doc.createElementNS(JBI_NAMESPACE, JBI_PREFIX + JBI_ENDPOINT_REFERENCE); epr.setAttributeNS(XMLNS_NAMESPACE, "xmlns:sns", getServiceName().getNamespaceURI()); epr.setAttributeNS(JBI_NAMESPACE, JBI_PREFIX + JBI_SERVICE_NAME, "sns:" + getServiceName().getLocalPart()); epr.setAttributeNS(JBI_NAMESPACE, JBI_PREFIX + JBI_ENDPOINT_NAME, getEndpointName()); fragment.appendChild(epr); return fragment; } catch (Exception e) { LOG.warn("Unable to create reference for ServiceEndpoint " + this, e); return null; } }
From source file:org.apache.shindig.gadgets.servlet.CajaContentRewriter.java
public void rewrite(Gadget gadget, MutableContent mc) { if (!cajaEnabled(gadget)) return;//from w w w. j a v a 2 s. c om GadgetContext gadgetContext = gadget.getContext(); boolean debug = gadgetContext.getDebug(); Document doc = mc.getDocument(); // Serialize outside of MutableContent, to prevent a re-parse. String docContent = HtmlSerialization.serialize(doc); String cacheKey = HashUtil.checksum(docContent.getBytes()); Node root = doc.createDocumentFragment(); root.appendChild(doc.getDocumentElement()); Node cajoledData = null; if (cajoledCache != null && !debug) { Element cajoledOutput = cajoledCache.getElement(cacheKey); if (cajoledOutput != null) { cajoledData = doc.adoptNode(cajoledOutput); createContainerFor(doc, cajoledData); mc.documentChanged(); } } if (cajoledData == null) { UriFetcher fetcher = makeFetcher(gadget); UriPolicy policy = makePolicy(gadget); URI javaGadgetUri = gadgetContext.getUrl().toJavaUri(); MessageQueue mq = new SimpleMessageQueue(); MessageContext context = new MessageContext(); PluginMeta meta = new PluginMeta(fetcher, policy); PluginCompiler compiler = makePluginCompiler(meta, mq); compiler.setMessageContext(context); if (debug) { // This will load cajita-debugmode.js gadget.addFeature("caja-debug"); compiler.setGoals(compiler.getGoals().without(PipelineMaker.ONE_CAJOLED_MODULE) .with(PipelineMaker.ONE_CAJOLED_MODULE_DEBUG)); } InputSource is = new InputSource(javaGadgetUri); boolean safe = false; compiler.addInput(new Dom(root), javaGadgetUri); try { if (!compiler.run()) { throw new GadgetRewriteException("Gadget has compile errors"); } StringBuilder scriptBody = new StringBuilder(); CajoledModule cajoled = compiler.getJavascript(); TokenConsumer tc = debug ? new JsPrettyPrinter(new Concatenator(scriptBody)) : new JsMinimalPrinter(new Concatenator(scriptBody)); cajoled.render(new RenderContext(tc).withAsciiOnly(true).withEmbeddable(true)); tc.noMoreTokens(); Node html = compiler.getStaticHtml(); Element script = doc.createElementNS(Namespaces.HTML_NAMESPACE_URI, "script"); script.setAttributeNS(Namespaces.HTML_NAMESPACE_URI, "type", "text/javascript"); script.appendChild(doc.createTextNode(scriptBody.toString())); Element cajoledOutput = doc.createElement("div"); cajoledOutput.setAttribute("id", "cajoled-output"); cajoledOutput.setAttribute("classes", "g___"); cajoledOutput.setAttribute("style", "position: relative;"); cajoledOutput.appendChild(doc.adoptNode(html)); cajoledOutput.appendChild(tameCajaClientApi(doc)); cajoledOutput.appendChild(doc.adoptNode(script)); Element messagesNode = formatErrors(doc, is, docContent, mq, /* is invisible */ false); cajoledOutput.appendChild(messagesNode); if (cajoledCache != null && !debug) { cajoledCache.addElement(cacheKey, cajoledOutput); } cajoledData = cajoledOutput; createContainerFor(doc, cajoledData); mc.documentChanged(); safe = true; HtmlSerialization.attach(doc, htmlSerializer, null); } catch (GadgetRewriteException e) { // There were cajoling errors // Content is only used to produce useful snippets with error messages createContainerFor(doc, formatErrors(doc, is, docContent, mq, true /* visible */)); logException(e, mq); safe = true; } finally { if (!safe) { // Fail safe mc.setContent(""); } } } }
From source file:org.apache.ws.security.saml.ext.OpenSAMLUtil.java
/** * Convert a SAML Assertion from a XMLObject to a DOM Element * * @param xmlObject of type XMLObject//w ww. j a va 2 s . co m * @param doc of type Document * @param signObject whether to sign the XMLObject during marshalling * @return Element * @throws MarshallingException * @throws SignatureException */ public static Element toDom(XMLObject xmlObject, Document doc, boolean signObject) throws WSSecurityException { Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject); Element element = null; DocumentFragment frag = doc == null ? null : doc.createDocumentFragment(); try { if (frag != null) { while (doc.getFirstChild() != null) { frag.appendChild(doc.removeChild(doc.getFirstChild())); } } try { if (doc == null) { element = marshaller.marshall(xmlObject); } else { element = marshaller.marshall(xmlObject, doc); } } catch (MarshallingException ex) { throw new WSSecurityException("Error marshalling a SAML assertion", ex); } if (signObject) { signXMLObject(xmlObject); } } finally { if (frag != null) { while (doc.getFirstChild() != null) { doc.removeChild(doc.getFirstChild()); } doc.appendChild(frag); } } return element; }
From source file:org.cauldron.einstein.ri.core.model.data.xml.dom.DOMUtil.java
@Post @Pre//from ww w . j a v a 2 s .c o m static DocumentFragment createDOMFromObject(List<DataObject> objects) { log.debug("Creating XMLDOM DataList."); DocumentBuilder docBuilder = null; try { docBuilder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new DataConversionRuntimeException(e); } DocumentFragment fragment; Document doc = docBuilder.newDocument(); fragment = doc.createDocumentFragment(); for (DataObject dataObject : objects) { final XMLDOMDataObject object = (XMLDOMDataObject) EinsteinRIRuntimeFactory.getInstance().getRuntime() .getRosettaStone().convert(XMLDOMDataModel.class, dataObject); final Node node = object.getNode(); doc.adoptNode(node); fragment.appendChild(node); } return fragment; }
From source file:org.cauldron.einstein.ri.core.model.data.xml.dom.DOMUtil.java
@Post @Pre/*from w ww . ja v a2 s. c o m*/ static Node createDOMFromObject(Object o) { Document doc; try { DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); if (o instanceof String) { log.debug("Creating XMLDOM DataObject from String"); doc = docBuilder.parse(new ByteArrayInputStream(((String) o).getBytes())); } else if (o instanceof byte[]) { log.debug("Creating XMLDOM DataObject from byte[]"); doc = docBuilder.parse(new ByteArrayInputStream((byte[]) o)); } else if (o instanceof InputStream) { log.debug("Creating XMLDOM DataObject from InpuStream"); doc = docBuilder.parse((InputStream) o); // } else if (o instanceof NodeList) { // log.debug("Creating XMLDOM DataObject from NodeList"); // if(true)throw new Error(); // NodeList nodeList = (NodeList) o; // fragment = buildFragmentFromNodeList(docBuilder, nodeList); // return fragment; } else if (o instanceof Node) { log.debug("Building fragment from a node."); return (Node) o; } else { log.debug("Creating XMLDOM DataObject from Object"); doc = docBuilder.parse(new ByteArrayInputStream(xstream.toXML(o).getBytes())); } } catch (ParserConfigurationException e) { throw new DataConversionRuntimeException(e); } catch (SAXException e) { throw new DataConversionRuntimeException(e); } catch (IOException e) { throw new DataConversionRuntimeException(e); // } catch (TransformerException e) { // throw new DataConversionRuntimeException(e); } final DocumentFragment fragment = doc.createDocumentFragment(); final Element element = doc.getDocumentElement(); fragment.getOwnerDocument().adoptNode(element); fragment.appendChild(element); return fragment; }
From source file:org.cauldron.einstein.ri.core.model.data.xml.dom.DOMUtil.java
@Post @Pre//from ww w.ja v a 2 s .co m public static DocumentFragment buildFragmentFromNodeList(DocumentBuilder docBuilder, NodeList nodeList) throws IOException, TransformerException, SAXException { Document doc; DocumentFragment fragment; /* I know this is convoluted but it's very difficult to actually add a bunch of random nodes to a document fragment without getting errors. This works by normalizing the nodes. */ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byteArrayOutputStream.write("<dummy>".getBytes()); Transformer xformer = transformerFactory.newTransformer(); xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); for (int i = 0; i < nodeList.getLength(); i++) { Source source = new DOMSource(nodeList.item(i)); Result result = new StreamResult(byteArrayOutputStream); xformer.transform(source, result); } byteArrayOutputStream.write("</dummy>".getBytes()); log.debug("Dumy node {0}.", byteArrayOutputStream); doc = docBuilder.parse(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); fragment = doc.createDocumentFragment(); nodeList = doc.getDocumentElement().getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { log.debug("Moving temporary node."); final Node node = nodeList.item(i); doc.adoptNode(node); fragment.appendChild(node); } log.debug("Fragment is now {0}.", fragment); return fragment; }
From source file:org.cauldron.einstein.ri.core.model.data.xml.dom.DOMUtil.java
@Post @Pre//www. j av a2s . c om public static DocumentFragment buildFragmentFromNode(DocumentBuilder docBuilder, Node node) throws IOException, TransformerException, SAXException { Document doc; DocumentFragment fragment; /* I know this is convoluted but it's very difficult to actually add a bunch of random nodes to a document fragment without getting errors. XML DOM APIs are bloomin sketchy so this guarantees that the node can be added. Need to throw this rubbish away and use a better XML API really. */ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byteArrayOutputStream.write("<dummy>".getBytes()); Transformer xformer = transformerFactory.newTransformer(); xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); Source source = new DOMSource(node); Result result = new StreamResult(byteArrayOutputStream); xformer.transform(source, result); byteArrayOutputStream.write("</dummy>".getBytes()); log.debug("Dumy node {0}.", byteArrayOutputStream); doc = docBuilder.parse(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); fragment = doc.createDocumentFragment(); final Element element = doc.getDocumentElement(); if (element.hasChildNodes()) { //has child nodes, not text. NodeList nodeList = element.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { log.debug("Moving temporary node."); final Node newNode = nodeList.item(i); doc.adoptNode(newNode); fragment.appendChild(newNode); } } log.debug("Fragment is now {0}.", ReflectionToStringBuilder.reflectionToString(fragment)); return fragment; }