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:bridge.toolkit.commands.S1000DConverter.java

/**
 * Receive the node, the DOM object and the new name of the node
 * // w w w. j a  v a 2 s .  c om
 * @param nodo
 * @param doc
 * @param newname
 */
public static Node changeNodename(Node nodo, org.w3c.dom.Document doc, String newname) {
    // Create an element with the new name
    Node element2 = doc.createElement(newname);

    // Copy the attributes to the new element
    NamedNodeMap attrs = nodo.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr2 = (Attr) doc.importNode(attrs.item(i), true);
        element2.getAttributes().setNamedItem(attr2);
    }

    // Move all the children
    while (nodo.hasChildNodes()) {
        element2.appendChild(nodo.getFirstChild());
    }

    // Replace the old node with the new node
    nodo.getParentNode().replaceChild(element2, nodo);
    return element2;

}

From source file:Main.java

/**
 * Try to normalize a document by removing nonsignificant whitespace.
 *
 * @see "#62006"/*from ww  w  .j  av a  2s. c  o  m*/
 */
private static Document normalize(Document orig) throws IOException {
    DocumentBuilder builder = null;
    DocumentBuilderFactory factory = getFactory(false, false);
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IOException("Cannot create parser satisfying configuration parameters: " + e, e); //NOI18N
    }

    DocumentType doctype = null;
    NodeList nl = orig.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        if (nl.item(i) instanceof DocumentType) {
            // We cannot import DocumentType's, so we need to manually copy it.
            doctype = (DocumentType) nl.item(i);
        }
    }
    Document doc;
    if (doctype != null) {
        doc = builder.getDOMImplementation().createDocument(orig.getDocumentElement().getNamespaceURI(),
                orig.getDocumentElement().getTagName(),
                builder.getDOMImplementation().createDocumentType(orig.getDoctype().getName(),
                        orig.getDoctype().getPublicId(), orig.getDoctype().getSystemId()));
        // XXX what about entity decls inside the DOCTYPE?
        doc.removeChild(doc.getDocumentElement());
    } else {
        doc = builder.newDocument();
    }
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (!(node instanceof DocumentType)) {
            try {
                doc.appendChild(doc.importNode(node, true));
            } catch (DOMException x) {
                // Thrown in NB-Core-Build #2896 & 2898 inside GeneratedFilesHelper.applyBuildExtensions
                throw new IOException("Could not import or append " + node + " of " + node.getClass(), x);
            }
        }
    }
    doc.normalize();
    nl = doc.getElementsByTagName("*"); // NOI18N
    for (int i = 0; i < nl.getLength(); i++) {
        Element e = (Element) nl.item(i);
        removeXmlBase(e);
        NodeList nl2 = e.getChildNodes();
        for (int j = 0; j < nl2.getLength(); j++) {
            Node n = nl2.item(j);
            if (n instanceof Text && ((Text) n).getNodeValue().trim().length() == 0) {
                e.removeChild(n);
                j--; // since list is dynamic
            }
        }
    }
    return doc;
}

From source file:DOMImport.java

public void importName(Document doc1, Document doc2) {
    Element root1 = doc1.getDocumentElement();
    Element personInDoc1 = (Element) root1.getFirstChild();

    Node importedPerson = doc2.importNode(personInDoc1, true);

    Element root2 = doc2.getDocumentElement();
    root2.appendChild(importedPerson);//from  ww w .  jav  a  2  s.co m
}

From source file:be.e_contract.mycarenet.xkms.ProofOfPossessionSignatureSOAPHandler.java

private Document copyDocument(Element element) throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    Node importedNode = document.importNode(element, true);
    document.appendChild(importedNode);/*  www. j ava  2  s . c  o  m*/
    return document;
}

From source file:de.betterform.xml.dom.DOMUtil.java

public static Node importAndAppendNode(Document document, Node toImport) {
    if (toImport != null) {
        Node imported = document.importNode(toImport, true);
        //            Node root = document.getDocumentElement();
        return document.appendChild(imported);
    }//w  w  w.  j  a v  a 2s. co  m
    return null;
}

From source file:de.betterform.connector.ModelSubmissionHandler.java

/**
 * Purpose:<br/>//from w  w w  .j av  a 2s .c om
 * The ModelSubmissionHandler can be used to exchange data between XForms models. It is capable of replacing data
 * in a certain instance of the receiver model.<br/><br/>
 *
 * Syntax: model:[Model ID]#instance('[Instance ID]')/[XPath]<br/><br/>
 *
 * Caveats:<br/>
 * - Model and Instance IDs must be known to allow explicit addressing<br/>
 * - the form author has to make sure that no ID collisions take place<br/>
 * - the XPath must be explicitly given even if the the target Node is the root Node of the instance
 *
 *
 * @param submission the submission issuing the request.
 * @param instance   the instance data to be serialized and submitted.
 * @return
 * @throws de.betterform.xml.xforms.exception.XFormsException
 *          if any error occurred during submission.
 */

public Map submit(Submission submission, Node instance) throws XFormsException {
    try {
        String replaceMode = submission.getReplace();
        if (!(replaceMode.equals("none") || replaceMode.equals("instance"))) {
            throw new XFormsException(
                    "ModelSubmissionHandler only supports 'none' or 'instance' as replace mode");
        }

        String submissionMethod = submission.getMethod();
        String resourceAttr = getURI();
        String resourceModelId = null;
        String instanceId = null;
        String xpath = null;

        try {
            int devider = resourceAttr.indexOf("#");
            resourceModelId = resourceAttr.substring(resourceAttr.indexOf(":") + 1, devider);

            int instanceIdStart = resourceAttr.indexOf("(") + 1;
            int instanceIdEnd = resourceAttr.indexOf(")");
            instanceId = resourceAttr.substring(instanceIdStart + 1, instanceIdEnd - 1);
            if (resourceAttr.indexOf("/") != -1) {
                xpath = resourceAttr.substring(resourceAttr.indexOf("/"));
            } else {
                throw new XFormsException(
                        "Syntax error: xpath mustn't be null. You've to provide at least the path to the rootnode.");
            }
        } catch (IndexOutOfBoundsException e) {
            throw new XFormsException("Syntax error in expression: " + resourceAttr);
        }

        Model providerModel;
        Model receiverModel;
        if (submissionMethod.equalsIgnoreCase("get")) {
            providerModel = submission.getContainerObject().getModel(resourceModelId);
            receiverModel = submission.getModel();
            Node targetNode = XPathUtil.getAsNode(XPathCache.getInstance().evaluate(
                    providerModel.getInstance(instanceId).getRootContext().getNodeset(), 1, xpath,
                    providerModel.getPrefixMapping(), providerModel.getXPathFunctionContext()), 1);

            if (targetNode == null) {
                throw new XFormsException("targetNode for xpath: " + xpath + " not found");
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("targetNode to replace............");
                DOMUtil.prettyPrintDOM(targetNode);
            }

            Document result = DOMUtil.newDocument(true, false);
            result.appendChild(result.importNode(targetNode.cloneNode(true), true));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("result Instance after insertion ............");
                DOMUtil.prettyPrintDOM(result);
            }

            Map response = new HashMap(1);
            response.put(XFormsProcessor.SUBMISSION_RESPONSE_DOCUMENT, result);
            return response;
        } else if (submissionMethod.equalsIgnoreCase("post")) {
            providerModel = submission.getModel();

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Instance Data to post............");
                DOMUtil.prettyPrintDOM(instance);
            }

            receiverModel = submission.getContainerObject().getModel(resourceModelId);
            Node targetNode = XPathUtil.getAsNode(XPathCache.getInstance().evaluate(
                    receiverModel.getInstance(instanceId).getRootContext().getNodeset(), 1, xpath,
                    receiverModel.getPrefixMapping(), receiverModel.getXPathFunctionContext()), 1);

            if (targetNode == null) {
                throw new XFormsException("targetNode for xpath: " + xpath + " not found");
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("targetNode to replace............");
                DOMUtil.prettyPrintDOM(targetNode);
            }
            //todo:review - this can be an Eleement if ref was used on submission!!!
            if (instance instanceof Document) {
                Document toImport = (Document) instance;
                targetNode.getParentNode().replaceChild(
                        targetNode.getOwnerDocument().importNode(toImport.getDocumentElement(), true),
                        targetNode);
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("result Instance after insertion ............");
                DOMUtil.prettyPrintDOM(receiverModel.getDefaultInstance().getInstanceDocument());
            }
        } else {
            throw new XFormsException("Submission method '" + submissionMethod + "' not supported");
        }
        receiverModel.rebuild();
        receiverModel.recalculate();
        receiverModel.revalidate();
        receiverModel.refresh();

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

From source file:de.betterform.xml.dom.DOMUtil.java

/**
 * This is a workaround for very strange behaviour of xerces-1.4.2 DOM importNode.
 *//*from   ww w . j a v a  2 s. co m*/
public static Node importNode(Document document, Node toImport) {
    if (toImport != null) {
        Node root = toImport.cloneNode(false); // no deep cloning!

        root = document.importNode(root, false);

        for (Node n = toImport.getFirstChild(); n != null; n = n.getNextSibling()) {
            root.appendChild(document.importNode(n, true));
        }

        return root;
    }

    return null;
}

From source file:com.adaptris.core.services.splitter.XpathMessageSplitter.java

@Override
public List<AdaptrisMessage> splitMessage(AdaptrisMessage msg) throws CoreException {
    List<AdaptrisMessage> result = new ArrayList<AdaptrisMessage>();
    try {/* w w  w .j a  v a 2  s  .  c o  m*/
        NamespaceContext namespaceCtx = SimpleNamespaceContext.create(getNamespaceContext(), msg);
        DocumentBuilderFactoryBuilder factoryBuilder = documentFactoryBuilder();
        if (namespaceCtx != null) {
            factoryBuilder = documentFactoryBuilder().withNamespaceAware(true);
        }
        DocumentBuilder docBuilder = factoryBuilder.configure(DocumentBuilderFactory.newInstance())
                .newDocumentBuilder();
        XmlUtils xml = new XmlUtils(namespaceCtx,
                factoryBuilder.configure(DocumentBuilderFactory.newInstance()));
        NodeList list = resolveXpath(msg, namespaceCtx, factoryBuilder);
        String encodingToUse = evaluateEncoding(msg);
        for (int i = 0; i < list.getLength(); i++) {
            Document splitXmlDoc = docBuilder.newDocument();
            Node e = list.item(i);
            Node dup = splitXmlDoc.importNode(e, true);
            splitXmlDoc.appendChild(dup);
            AdaptrisMessage splitMsg = selectFactory(msg).newMessage("", encodingToUse);
            try (Writer writer = splitMsg.getWriter()) {
                xml.writeDocument(splitXmlDoc, writer, encodingToUse);
                copyMetadata(msg, splitMsg);
                result.add(splitMsg);
            }
        }
    } catch (Exception e) {
        throw new CoreException(e);
    } finally {

    }
    return result;
}

From source file:com.msopentech.odatajclient.engine.data.json.JSONPropertySerializer.java

/**
 * {@inheritDoc }/*from ww  w.j av a 2 s .c o  m*/
 */
@Override
public void serialize(final JSONProperty property, final JsonGenerator jgen, final SerializerProvider provider)
        throws IOException, JsonProcessingException {

    jgen.writeStartObject();

    if (property.getMetadata() != null) {
        jgen.writeStringField(ODataConstants.JSON_METADATA, property.getMetadata().toASCIIString());
    }

    final Element content = property.getContent();
    if (XMLUtils.hasOnlyTextChildNodes(content)) {
        jgen.writeStringField(ODataConstants.JSON_VALUE, content.getTextContent());
    } else {
        try {
            final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
            final Document document = builder.newDocument();
            final Element wrapper = document.createElement(ODataConstants.ELEM_PROPERTY);

            if (XMLUtils.hasElementsChildNode(content)) {
                wrapper.appendChild(document.renameNode(document.importNode(content, true), null,
                        ODataConstants.JSON_VALUE));

                DOMTreeUtils.writeSubtree(jgen, wrapper);
            } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                wrapper.appendChild(document.renameNode(document.importNode(content, true), null,
                        ODataConstants.JSON_VALUE));

                DOMTreeUtils.writeSubtree(jgen, wrapper, true);
            } else {
                DOMTreeUtils.writeSubtree(jgen, content);
            }
        } catch (Exception e) {
            throw new JsonParseException("Cannot serialize property", JsonLocation.NA, e);
        }
    }

    jgen.writeEndObject();
}

From source file:com.nortal.jroad.endpoint.AbstractXTeeBaseEndpoint.java

protected Document parseQuery(SOAPMessage queryMsg) throws Exception {
    Node bodyNode = SOAPUtil.getFirstNonTextChild(queryMsg.getSOAPBody());
    if (XRoadProtocolVersion.V2_0 == version) {
        bodyNode = SOAPUtil.getNodeByXPath(bodyNode, "//keha");
        if (bodyNode == null) {
            throw new IllegalStateException(
                    "Service is not metaservice, but query is missing mandatory body ('//keha\')");
        }//from ww w  . j a v  a2s  .co m
    }

    Document query = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    bodyNode = query.importNode(bodyNode, true);
    query.appendChild(bodyNode);
    return query;
}