Example usage for org.w3c.dom Document importNode

List of usage examples for org.w3c.dom Document importNode

Introduction

In this page you can find the example usage for org.w3c.dom Document importNode.

Prototype

public Node importNode(Node importedNode, boolean deep) throws DOMException;

Source Link

Document

Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node.

Usage

From source file:org.chiba.xml.xforms.Instance.java

/**
 * Returns a new created instance document.
 * <p/>/*from  w  w  w  .  ja va 2s . c om*/
 * If this instance has an original instance, it will be imported into this new document. Otherwise the new document
 * is left empty.
 *
 * @return a new created instance document.
 */
private Document createInstanceDocument() throws XFormsException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        Document document = factory.newDocumentBuilder().newDocument();

        if (this.initialInstance != null) {
            document.appendChild(document.importNode(this.initialInstance.cloneNode(true), true));

            if (!this.element.hasAttributeNS(NamespaceCtx.XFORMS_NS, SRC_ATTRIBUTE)) {
                // apply namespaces
                NamespaceCtx.applyNamespaces(this.element, document.getDocumentElement());
            }
        }

        return document;
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:org.commonjava.maven.plugins.monolith.handler.ComponentsXmlHandler.java

private void addToArchive(final Archiver archiver) throws IOException, ArchiverException {
    if (components != null) {
        final File f = File.createTempFile("maven-assembly-plugin", "tmp");
        f.deleteOnExit();/* w w w .  j  a v  a  2s .com*/

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(f);
            final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            final Element cset = document.createElement("component-set");
            document.appendChild(cset);

            final Element cs = document.createElement("components");
            cset.appendChild(cs);

            for (final Element component : components.values()) {
                final Element c = (Element) document.importNode(component, true);
                cs.appendChild(c);
            }

            writeDocument(document, out);
        } catch (final TransformerException e) {
            throw new IOException(
                    "Failed to construct/write aggregated components.xml document: " + e.getMessage(), e);
        } catch (final ParserConfigurationException e) {
            throw new IOException(
                    "Failed to construct/write aggregated components.xml document: " + e.getMessage(), e);
        } finally {
            closeQuietly(out);
        }

        archiver.addFile(f, COMPONENTS_XML_PATH);
    }
}

From source file:org.craftercms.cstudio.share.forms.impl.FormServiceBaseImpl.java

/**
 * merge the instance data with the document
 * /*from   w  w w . ja va  2s. com*/
 * @param xformDocument
 * @param model
 * @return
 */
protected Document mergeInstanceDataWithForm(Document xformDocument, Map<String, Document> model,
        final String namespace) {

    Document retDocument = xformDocument;

    if (model != null) {

        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();

        try {

            NamespaceContext cstudio = new NamespaceContext() {

                public String getNamespaceURI(String prefix) {

                    String uri = "";
                    if (prefix.equals(namespace))
                        uri = "http://www.w3.org/2002/xforms";

                    return uri;
                }

                @SuppressWarnings("unchecked")
                public Iterator getPrefixes(String val) {

                    return null;
                }

                public String getPrefix(String uri) {

                    return null;
                }

            };

            xPath.setNamespaceContext(cstudio);
            XPathExpression xPathExpression = xPath.compile("//" + namespace + ":instance");

            // DOMSource source = new DOMSource(xformDocument);
            // StringWriter xmlAsWriter = new StringWriter();
            // StreamResult result = new StreamResult(xmlAsWriter);
            // TransformerFactory.newInstance().newTransformer().transform(source,
            // result);
            StringReader xmlReader = new StringReader(DomUtils.xmlToString(xformDocument));
            InputSource documentAsInputSource = new InputSource(xmlReader);

            // using implementation here, see article
            // http://onjava.com/pub/a/onjava/2005/01/12/xpath.html
            DTMNodeList nodes = (DTMNodeList) xPathExpression.evaluate(documentAsInputSource,
                    XPathConstants.NODESET);

            int nodeCount = nodes.getLength();

            for (int i = 0; i < nodeCount; i++) {
                Element currentNode = (Element) nodes.item(i);
                String modelId = currentNode.getAttribute("id");

                Document documentToInsert = model.get(modelId);

                if (documentToInsert != null) {

                    Element importedModelRoot = documentToInsert.getDocumentElement();

                    retDocument = currentNode.getOwnerDocument();
                    Node importedModel = retDocument.importNode(importedModelRoot, true);

                    currentNode.appendChild(importedModel);
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    return retDocument;
}

From source file:org.cruxframework.crux.core.declarativeui.ViewParser.java

/**
 * @param cruxPageDocument/*from  w  w  w.j  a  va  2  s  . co  m*/
 * @return
 */
private Document createHTMLDocument(Document cruxPageDocument) {
    Document htmlDocument;
    DocumentType doctype = cruxPageDocument.getDoctype();

    if (doctype != null
            || Boolean.parseBoolean(ConfigurationFactory.getConfigurations().enableGenerateHTMLDoctype())) {
        String name = doctype != null ? doctype.getName() : "HTML";
        String publicId = doctype != null ? doctype.getPublicId() : null;
        String systemId = doctype != null ? doctype.getSystemId() : null;

        DocumentType newDoctype = documentBuilder.getDOMImplementation().createDocumentType(name, publicId,
                systemId);
        htmlDocument = documentBuilder.getDOMImplementation().createDocument(XHTML_NAMESPACE, "html",
                newDoctype);
    } else {
        htmlDocument = documentBuilder.newDocument();
        Element cruxPageElement = cruxPageDocument.getDocumentElement();
        Node htmlElement = htmlDocument.importNode(cruxPageElement, false);
        htmlDocument.appendChild(htmlElement);
    }

    String manifest = cruxPageDocument.getDocumentElement().getAttribute("manifest");
    if (!StringUtils.isEmpty(manifest)) {
        htmlDocument.getDocumentElement().setAttribute("manifest", manifest);
    }
    return htmlDocument;
}

From source file:org.csstudio.utility.batik.SVGHandler.java

private Document createWrapper(final SVGDocument doc) {
    // creation of the SVG document
    String svgNamespace = SVGDOMImplementation.SVG_NAMESPACE_URI;
    DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
    final Document newDocument = impl.createDocument(svgNamespace, "svg", null);

    // get the root element
    svgRootNode = newDocument.getDocumentElement();
    mainGraphicNode = newDocument.createElementNS(svgNamespace, "g");

    // attach the root of original doc to transform to the root
    Node copiedRoot = newDocument.importNode(doc.getDocumentElement(), true);
    mainGraphicNode.appendChild(copiedRoot);
    svgRootNode.appendChild(mainGraphicNode);
    updateMatrix();//from   w w  w  . j  a  va 2s.  c om
    return newDocument;
}

From source file:org.dita.dost.reader.ChunkMapReader.java

private Document buildOutputDocument(final Element root) {
    final Document doc = XMLUtils.getDocumentBuilder().newDocument();
    if (workdir != null) {
        doc.appendChild(doc.importNode(workdir, true));
    }/*from ww w.  jav a2 s. c  o m*/
    if (workdirUrl != null) {
        doc.appendChild(doc.importNode(workdirUrl, true));
    }
    if (path2proj != null) {
        doc.appendChild(doc.importNode(path2proj, true));
    }
    if (path2projUrl != null) {
        doc.appendChild(doc.importNode(path2projUrl, true));
    }
    doc.appendChild(doc.importNode(root, true));
    return doc;
}

From source file:org.docx4j.convert.in.xhtml.XHTMLImporter.java

/**
 * @param node/*from   w  w w .j ava 2s  .c o m*/
 * @param baseUrl
 * @param wordMLPackage
 * @return
 * @throws IOException
 */
public static List<Object> convert(Node node, String baseUrl, WordprocessingMLPackage wordMLPackage)
        throws Docx4JException {
    XHTMLImporter importer = new XHTMLImporter(wordMLPackage);

    importer.renderer = new DocxRenderer();
    if (node instanceof Document) {
        importer.renderer.setDocument((Document) node, baseUrl);
    } else {
        Document doc = XmlUtils.neww3cDomDocument();
        doc.importNode(node, true);
        importer.renderer.setDocument(doc, baseUrl);
    }
    importer.renderer.layout();

    importer.traverse(importer.renderer.getRootBox(), importer.imports, null);

    return importer.imports;
}

From source file:org.docx4j.XmlUtils.java

/**
 * @param docBuilder/*ww  w.  j  a  v a2 s .  co  m*/
 *          the parser
 * @param parent
 *          node to add fragment to
 * @param fragment
 *          a well formed XML fragment
* @throws ParserConfigurationException 
 */
public static void appendXmlFragment(Document document, Node parent, String fragment)
        throws IOException, SAXException, ParserConfigurationException {

    Node fragmentNode = XmlUtils.getNewDocumentBuilder().parse(new InputSource(new StringReader(fragment)))
            .getDocumentElement();

    fragmentNode = document.importNode(fragmentNode, true);

    parent.appendChild(fragmentNode);
}

From source file:org.eclipse.ecr.common.xmap.DOMHelper.java

/**
 * Parses a string containing XML and returns a DocumentFragment containing
 * the nodes of the parsed XML./* w ww . ja  v  a 2s  .  c o  m*/
 */
public static void loadFragment(Element el, String fragment) {
    // Wrap the fragment in an arbitrary element
    fragment = "<fragment>" + fragment + "</fragment>";
    try {
        // Create a DOM builder and parse the fragment
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document d = factory.newDocumentBuilder().parse(new InputSource(new StringReader(fragment)));

        Document doc = el.getOwnerDocument();

        // Import the nodes of the new document into doc so that they
        // will be compatible with doc
        Node node = doc.importNode(d.getDocumentElement(), true);

        // Create the document fragment node to hold the new nodes
        DocumentFragment docfrag = doc.createDocumentFragment();

        // Move the nodes into the fragment
        while (node.hasChildNodes()) {
            el.appendChild(node.removeChild(node.getFirstChild()));
        }

    } catch (Exception e) {
        log.error(e, e);
    }
}

From source file:org.eclipse.skalli.view.internal.servlet.StaticContentServlet.java

/**
 * Resolves all &lt;include&gt; in a given schema and writes the
 * result to the given output stream. Includes that can't be resolved
 * are removed from the schema.//from  w w  w  .  jav a 2 s. c o m
 * @param in  the input stream providing the schema to resolve.
 * @param out  the output stream to write the result to.
 * @throws IOException  if an i/o error occured.
 * @throws SAXException  if parsing of the schema failed.
 * @throws ParserConfigurationException  indicates a serious parser configuration error.
 * @throws TransformerException  if transforming the schema DOM to a character stream failed.
 * @throws TransformerConfigurationException  indicates a serious transformer configuration error.
 */
private void resolveIncludes(InputStream in, OutputStream out) throws IOException, SAXException,
        ParserConfigurationException, TransformerConfigurationException, TransformerException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document schemaDOM = dbf.newDocumentBuilder().parse(new InputSource(in));
    Element schemaRoot = schemaDOM.getDocumentElement();

    // iterate all <include> tags and resolve them if possible
    NodeList includes = schemaDOM.getElementsByTagName("xsd:include");
    while (includes.getLength() > 0) {
        for (int i = 0; i < includes.getLength(); ++i) {
            Node includeNode = includes.item(i);
            Node includeParent = includeNode.getParentNode();
            Node schemaLocation = includeNode.getAttributes().getNamedItem("schemaLocation");
            if (schemaLocation != null) {
                // extract the pure file name from the schemaLocation and
                // try to find an XSD resource in all model extensions matching
                // the given schemaLocation attribute -> if found, replace the include tag
                // with the DOM of the include (without the root tag, of course!)
                URL includeFile = RestUtils.findSchemaResource(schemaLocation.getTextContent());
                if (includeFile != null) {
                    Document includeDOM = dbf.newDocumentBuilder()
                            .parse(new InputSource(includeFile.openStream()));
                    NodeList includeNodes = includeDOM.getDocumentElement().getChildNodes();
                    for (int j = 0; j < includeNodes.getLength(); ++j) {
                        // import and insert the tag before <include>
                        schemaRoot.insertBefore(schemaDOM.importNode(includeNodes.item(j), true), includeNode);
                    }
                }

                // in any case: remove the <include> tag
                includeParent.removeChild(includeNode);
            }
        }
        // resolve includes of includes (if any)
        includes = schemaDOM.getElementsByTagName("xsd:include");
    }

    // serialize the schema DOM to the given output stream
    Transformer xform = TransformerFactory.newInstance().newTransformer();
    xform.setOutputProperty(OutputKeys.INDENT, "yes");
    xform.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    xform.transform(new DOMSource(schemaDOM), new StreamResult(out));
}