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:net.sf.jasperreports.engine.util.JRXmlUtils.java

/**
 * Creates a document having a node as root.
 * //w  w w.j a v a  2s  . c  om
 * @param sourceNode the node
 * @return a document having the specified node as root
 * @throws JRException
 */
public static Document createDocument(Node sourceNode, boolean isNamespaceAware) throws JRException {
    Document doc = JRXmlUtils.createDocumentBuilder(isNamespaceAware).newDocument();
    Node source;
    if (sourceNode.getNodeType() == Node.DOCUMENT_NODE) {
        source = ((Document) sourceNode).getDocumentElement();
    } else {
        source = sourceNode;
    }

    Node node = doc.importNode(source, true);
    doc.appendChild(node);

    return doc;
}

From source file:Main.java

/**
 * Rename an element in a DOM document. It happens to involves a node
 * replication.//from ww  w .  ja va  2  s.com
 * 
 * @param document
 *            The document containing the element (some way to verify
 *            that?).
 */
public static Element renameElement(Document document, Element element, String newName, String namespace) {
    if (namespace == null) {
        throw new IllegalArgumentException("No namespace provided for element " + element);
    }
    Element newElement = document.createElementNS(namespace, newName);
    NamedNodeMap attributes = element.getAttributes();
    for (int i = 0, iEnd = attributes.getLength(); i < iEnd; i++) {
        Attr attr2 = (Attr) document.importNode(attributes.item(i), true);
        newElement.getAttributes().setNamedItem(attr2);
    }
    while (element.hasChildNodes()) {
        newElement.appendChild(element.getFirstChild());
    }
    element.getParentNode().replaceChild(newElement, element);
    return newElement;
}

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * @param commentsDom//from  w  w w  .  j av a  2  s  .c  o  m
 * @param commentTemplate
 * @param messageText
 * @param commentId
 */
static void addCommentToComments(Document commentsDom, Element commentTemplate, String messageText,
        String commentId) {
    Element comment = (Element) commentsDom.importNode(commentTemplate, true);
    commentsDom.getDocumentElement().appendChild(comment);
    comment.setAttributeNS(wNs, "w:id", commentId);
    comment.setAttributeNS(wNs, "w:author", "XML Validator");
    comment.setAttributeNS(wNs, "w:initials", "XMLVal");
    comment.setAttributeNS(wNs, "w:date", timestampFormatter.format(Calendar.getInstance().getTime()));
    Element elem = DataUtil.getElementNS(comment, wNs, "p");
    NodeList nl = elem.getElementsByTagNameNS(wNs, "r");
    elem = (Element) nl.item(nl.getLength() - 1);
    Element text = DataUtil.getElementNS(elem, wNs, "t");
    text.setTextContent(messageText);
}

From source file:at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient.java

private static Element packIntoSOAP(Element element) throws MISSimpleClientException {
    try {//from   w ww .ja va 2  s  .  c  o  m
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element soapEnvelope = doc.createElement("Envelope");
        soapEnvelope.setAttribute("xmlns", SOAP_NS);
        Element soapBody = doc.createElement("Body");
        soapEnvelope.appendChild(soapBody);
        soapBody.appendChild(doc.importNode(element, true));
        return soapEnvelope;
    } catch (ParserConfigurationException e) {
        throw new MISSimpleClientException("service.06", e);
    }
}

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

private static Rule wrap(InsertElementRule r) {
    return new Rule(r.xpath(), r.id()) {
        @Override// w  w w. j ava  2s.  c o m
        public void apply(Document document, Node matchedNode) throws Exception {
            final Document newDocument = parseXMLFragment(r.insert());
            final Node firstChild = newDocument.getFirstChild();
            final Node adoptedNode = document.importNode(firstChild, true);
            matchedNode.appendChild(adoptedNode);
        }

        @Override
        public String toString() {
            return "INSERT ELEMENT: " + r.xpath() + " with '" + r.insert();
        }
    };
}

From source file:de.mpg.escidoc.services.syndication.Utils.java

public static Document createDocument(Node sourceNode) throws Exception {
    Document doc = createDocumentBuilder().newDocument();
    Node source;//from   w  w w  . jav a  2 s . co  m
    if (sourceNode.getNodeType() == Node.DOCUMENT_NODE) {
        source = ((Document) sourceNode).getDocumentElement();
    } else {
        source = sourceNode;
    }

    Node node = doc.importNode(source, true);
    doc.appendChild(node);

    return doc;
}

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

public static void serialize(final JsonGenerator jgen, final Element node, final String type)
        throws IOException {
    final EdmSimpleType edmSimpleType = EdmSimpleType.fromValue(type);

    if (edmSimpleType.equals(EdmSimpleType.GeographyCollection)
            || edmSimpleType.equals(EdmSimpleType.GeometryCollection)) {

        jgen.writeStringField(ODataConstants.ATTR_TYPE, EdmSimpleType.GeometryCollection.name());
    } else {//from  w  w w .  j  a  va  2s  .c  o  m
        final int yIdx = edmSimpleType.name().indexOf('y');
        final String itemType = edmSimpleType.name().substring(yIdx + 1);
        jgen.writeStringField(ODataConstants.ATTR_TYPE, itemType);
    }

    Element root = null;
    switch (edmSimpleType) {
    case GeographyPoint:
    case GeometryPoint:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_POINT).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
        serializePoint(jgen, XMLUtils.getChildElements(root, ODataConstants.ELEM_POS).get(0));
        jgen.writeEndArray();
        break;

    case GeographyMultiPoint:
    case GeometryMultiPoint:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTIPOINT).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);

        final List<Element> pMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_POINTMEMBERS);
        if (pMembs != null && !pMembs.isEmpty()) {
            for (Element point : XMLUtils.getChildElements(pMembs.get(0), ODataConstants.ELEM_POINT)) {
                jgen.writeStartArray();
                serializePoint(jgen, XMLUtils.getChildElements(point, ODataConstants.ELEM_POS).get(0));
                jgen.writeEndArray();
            }
        }

        jgen.writeEndArray();
        break;

    case GeographyLineString:
    case GeometryLineString:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_LINESTRING).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
        serializeLineString(jgen, root);
        jgen.writeEndArray();
        break;

    case GeographyMultiLineString:
    case GeometryMultiLineString:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTILINESTRING).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);

        final List<Element> lMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_LINESTRINGMEMBERS);
        if (lMembs != null && !lMembs.isEmpty()) {
            for (Element lineStr : XMLUtils.getChildElements(lMembs.get(0), ODataConstants.ELEM_LINESTRING)) {
                jgen.writeStartArray();
                serializeLineString(jgen, lineStr);
                jgen.writeEndArray();
            }
        }

        jgen.writeEndArray();
        break;

    case GeographyPolygon:
    case GeometryPolygon:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_POLYGON).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
        serializePolygon(jgen, root);
        jgen.writeEndArray();
        break;

    case GeographyMultiPolygon:
    case GeometryMultiPolygon:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTIPOLYGON).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);

        final List<Element> mpMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_SURFACEMEMBERS);
        if (mpMembs != null & !mpMembs.isEmpty()) {
            for (Element pol : XMLUtils.getChildElements(mpMembs.get(0), ODataConstants.ELEM_POLYGON)) {
                jgen.writeStartArray();
                serializePolygon(jgen, pol);
                jgen.writeEndArray();
            }
        }

        jgen.writeEndArray();
        break;

    case GeographyCollection:
    case GeometryCollection:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_GEOCOLLECTION).get(0);

        final List<Element> cMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_GEOMEMBERS);
        if (cMembs != null && !cMembs.isEmpty()) {
            jgen.writeArrayFieldStart(ODataConstants.JSON_GEOMETRIES);

            for (Node geom : XMLUtils.getChildNodes(cMembs.get(0), Node.ELEMENT_NODE)) {
                try {
                    final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
                    final Document doc = builder.newDocument();

                    final Element fakeParent = doc.createElementNS(ODataConstants.NS_DATASERVICES,
                            ODataConstants.PREFIX_DATASERVICES + "fake");
                    fakeParent.appendChild(doc.importNode(geom, true));

                    final EdmSimpleType callAsType = XMLUtils.simpleTypeForNode(
                            edmSimpleType == EdmSimpleType.GeographyCollection ? Geospatial.Dimension.GEOGRAPHY
                                    : Geospatial.Dimension.GEOMETRY,
                            geom);

                    jgen.writeStartObject();
                    serialize(jgen, fakeParent, callAsType.toString());
                    jgen.writeEndObject();
                } catch (Exception e) {
                    LOG.warn("While serializing {}", XMLUtils.getSimpleName(geom), e);
                }
            }

            jgen.writeEndArray();
        }
        break;

    default:
    }

    if (root != null) {
        serializeCrs(jgen, root);
    }
}

From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java

private static Element toPrimitivePropertyElement(final String name, final ODataPrimitiveValue value,
        final Document doc, final boolean setType) {

    final Element element = doc.createElement(ODataConstants.PREFIX_DATASERVICES + name);
    if (setType) {
        element.setAttribute(ODataConstants.ATTR_M_TYPE, value.getTypeName());
    }// www  .j a  v  a  2s  .  co  m

    if (value instanceof ODataGeospatialValue) {
        element.appendChild(doc.importNode(((ODataGeospatialValue) value).toTree(), true));
    } else {
        element.setTextContent(value.toString());
    }

    return element;
}

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

private static Rule wrap(ReplaceRule r) {
    final String newValue;

    if (!ContextRewritingBootStrapper.NULL_STRING.equals(r.replacement())) {
        if (r.replacementClassName() != ReplaceRule.NULL_CLASS) {
            throw new RuntimeException("Either replacement or replacementClassName needs to be set");
        }//from w  w w  .j av  a  2s  .  co  m
        newValue = r.replacement();
    } else if (r.replacementClassName() != ReplaceRule.NULL_CLASS) {
        newValue = r.replacementClassName().getName();
    } else {
        throw new RuntimeException(
                "You need to provide EITHER 'replacement' OR 'replacementClassName' attributes");
    }
    return new Rule(r.xpath(), r.id()) {
        public void apply(Document document, Node matchedNode) throws Exception {
            switch (matchedNode.getNodeType()) {
            case Node.ATTRIBUTE_NODE:
                matchedNode.setNodeValue(newValue);
                break;
            case Node.ELEMENT_NODE:
                final Document replDocument = parseXMLFragment(newValue);
                final Node firstChild = replDocument.getFirstChild();
                final Node adoptedNode = document.importNode(firstChild, true);
                matchedNode.getParentNode().replaceChild(adoptedNode, matchedNode);
                break;
            default:
                throw new RuntimeException();
            }
        }

        @Override
        public String toString() {
            return "REPLACE: " + r.xpath() + " with '" + newValue;
        }
    };
}

From source file:ee.ria.xroad.proxy.util.MetaserviceTestUtil.java

/** Merge xroad-specific {@link SoapHeader} to the generic {@link SOAPHeader}
 * @param header//from   w  ww.  j  a v a  2  s .  c om
 * @param xrHeader
 * @throws JAXBException
 * @throws ParserConfigurationException
 * @throws SOAPException
 */
public static void mergeHeaders(SOAPHeader header, SoapHeader xrHeader)
        throws JAXBException, ParserConfigurationException, SOAPException {

    Document document = documentBuilderFactory.newDocumentBuilder().newDocument();
    final DocumentFragment documentFragment = document.createDocumentFragment();
    // marshalling on the header would add the xroad header as a child of the header
    // (i.e. two nested header elements)
    marshaller.marshal(xrHeader, documentFragment);

    Document headerDocument = header.getOwnerDocument();
    Node xrHeaderElement = documentFragment.getFirstChild();

    assertTrue("test setup failed: assumed had header element but did not",
            xrHeaderElement.getNodeType() == Node.ELEMENT_NODE
                    && xrHeaderElement.getLocalName().equals("Header"));

    final NamedNodeMap attributes = xrHeaderElement.getAttributes();

    if (attributes != null) {
        for (int i = 0; i < attributes.getLength(); i++) {
            final Attr attribute = (Attr) attributes.item(i);
            header.setAttributeNodeNS((Attr) headerDocument.importNode(attribute, false));
        }
    }

    final NodeList childNodes = xrHeaderElement.getChildNodes();

    if (childNodes != null) {
        for (int i = 0; i < childNodes.getLength(); i++) {
            final Node node = childNodes.item(i);
            header.appendChild(headerDocument.importNode(node, true));
        }
    }

}