Example usage for org.w3c.dom Element appendChild

List of usage examples for org.w3c.dom Element appendChild

Introduction

In this page you can find the example usage for org.w3c.dom Element appendChild.

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:eu.europa.esig.dss.DSSXMLUtils.java

/**
 * Creates a DOM Document object of the specified type with its document elements.
 *
 * @param namespaceURI/* w  w w.j a  v a  2 s  .co  m*/
 * @param qualifiedName
 * @param element1
 * @param element2
 * @return {@code Document}
 */
public static Document createDocument(final String namespaceURI, final String qualifiedName,
        final Element element1, final Element element2) {
    ensureDocumentBuilder();

    DOMImplementation domImpl;
    try {
        domImpl = dbFactory.newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException e) {
        throw new DSSException(e);
    }
    final Document newDocument = domImpl.createDocument(namespaceURI, qualifiedName, null);
    final Element newElement = newDocument.getDocumentElement();
    newDocument.adoptNode(element1);
    newElement.appendChild(element1);

    newDocument.adoptNode(element2);
    newElement.appendChild(element2);

    return newDocument;
}

From source file:com.twinsoft.convertigo.engine.migration.Migration7_0_0.java

public static Element migrate(Document document, Element projectNode) throws EngineException {
    try {//www  .  java 2 s. co m
        NodeList mobileDevicesNodeList = XMLUtils.findElements(projectNode, "/mobiledevice");
        if (mobileDevicesNodeList != null) {
            MobileApplication mobileApplication = new MobileApplication();
            Element mobileApplicationElement = mobileApplication.toXml(document);
            projectNode.appendChild(mobileApplicationElement);

            Node[] mobileDeviceNodes = XMLUtils.toNodeArray(mobileDevicesNodeList);
            boolean hasAndroid = false;
            boolean hasIOs = false;

            for (Node mobileDeviceNode : mobileDeviceNodes) {
                Element mobileDevice = (Element) mobileDeviceNode;
                String classname = mobileDevice.getAttribute("classname");

                if (classname == null) {
                    // may never arrived
                } else if (classname.equals("com.twinsoft.convertigo.beans.mobiledevices.Android")) {
                    hasAndroid = true;
                } else if (classname.startsWith("com.twinsoft.convertigo.beans.mobiledevices.IP")) {
                    hasIOs = true;
                }

                projectNode.removeChild(mobileDevice);
            }

            if (hasAndroid) {
                mobileApplicationElement.appendChild(new Android().toXml(document));
            }
            if (hasIOs) {
                mobileApplicationElement.appendChild(new IOs().toXml(document));
            }
            if (hasAndroid && hasIOs) {
                mobileApplicationElement.appendChild(new WindowsPhone8().toXml(document));
                mobileApplicationElement.appendChild(new Windows().toXml(document));
            }

            String projectName = "" + XMLUtils.findPropertyValue(projectNode, "name");
            File mobileFolder = new File(Engine.PROJECTS_PATH + "/" + projectName + "/DisplayObjects/mobile");
            if (mobileFolder.exists()) {
                FileUtils.write(new File(mobileFolder, "mobile_project_migrated.txt"),
                        "Your mobile project has been migrated.\n"
                                + "Now, we make per platform configuration and resources.\n"
                                + "You may customize your config.xml (the existing one will never used) and dispatch your existing specific resources per platform (see the 'platforms' folder).\n"
                                + "You can delete this file after reading it.",
                        "UTF-8");
            }
        }
    } catch (Exception e) {
        throw new EngineException("[Migration 7.0.0] Unable to migrate project", e);
    }

    return projectNode;
}

From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java

/**
 * query to xml/*ww w. j  a  v a 2s.c  o m*/
 * 
 * @param userDB
 * @param strQuery
 * @param listParam
 */
@SuppressWarnings("deprecation")
public static String selectToXML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam)
        throws Exception {
    final StringWriter stWriter = new StringWriter();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.newDocument();
    final Element results = doc.createElement("Results");
    doc.appendChild(results);

    SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
    QueryRunner qr = new QueryRunner(client.getDataSource());
    qr.query(strQuery, listParam.toArray(), new ResultSetHandler<Object>() {

        @Override
        public Object handle(ResultSet rs) throws SQLException {
            ResultSetMetaData metaData = rs.getMetaData();

            while (rs.next()) {
                Element row = doc.createElement("Row");
                results.appendChild(row);
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(i) == null ? "" : rs.getObject(i);
                    Element node = doc.createElement(columnName);
                    node.appendChild(doc.createTextNode(value.toString()));
                    row.appendChild(node);
                }
            }

            return stWriter.toString();
        }
    });

    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setAttribute("indent-number", 4);

    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1");
    StreamResult sr = new StreamResult(stWriter);
    transformer.transform(domSource, sr);

    return stWriter.toString();
}

From source file:com.msopentech.odatajclient.engine.data.impl.JSONDOMTreeUtils.java

/**
 * Recursively builds DOM content out of JSON subtree rooted at given node.
 *
 * @param client OData client./*from   w  w  w  .jav  a 2 s . c  o  m*/
 * @param document root of the DOM document being built
 * @param parent parent of the nodes being generated during this step
 * @param node JSON node to be used as source for DOM elements
 */
public static void buildSubtree(final ODataClient client, final Element parent, final JsonNode node) {
    final Iterator<String> fieldNameItor = node.fieldNames();
    final Iterator<JsonNode> nodeItor = node.elements();
    while (nodeItor.hasNext()) {
        final JsonNode child = nodeItor.next();
        final String name = fieldNameItor.hasNext() ? fieldNameItor.next() : "";

        // no name? array item
        if (name.isEmpty()) {
            final Element element = parent.getOwnerDocument().createElementNS(
                    client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES),
                    ODataConstants.PREFIX_DATASERVICES + ODataConstants.ELEM_ELEMENT);
            parent.appendChild(element);

            if (child.isValueNode()) {
                if (child.isNull()) {
                    element.setAttributeNS(
                            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                            ODataConstants.ATTR_NULL, Boolean.toString(true));
                } else {
                    element.appendChild(parent.getOwnerDocument().createTextNode(child.asText()));
                }
            }

            if (child.isContainerNode()) {
                buildSubtree(client, element, child);
            }
        } else if (!name.contains("@") && !ODataConstants.JSON_TYPE.equals(name)) {
            final Element property = parent.getOwnerDocument().createElementNS(
                    client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES),
                    ODataConstants.PREFIX_DATASERVICES + name);
            parent.appendChild(property);

            boolean typeSet = false;
            if (node.hasNonNull(name + "@" + ODataConstants.JSON_TYPE)) {
                property.setAttributeNS(
                        client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                        ODataConstants.ATTR_M_TYPE,
                        node.get(name + "@" + ODataConstants.JSON_TYPE).textValue());
                typeSet = true;
            }

            if (child.isNull()) {
                property.setAttributeNS(
                        client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                        ODataConstants.ATTR_NULL, Boolean.toString(true));
            } else if (child.isValueNode()) {
                if (!typeSet) {
                    if (child.isInt()) {
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE, EdmSimpleType.Int32.toString());
                    }
                    if (child.isLong()) {
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE, EdmSimpleType.Int64.toString());
                    }
                    if (child.isBigDecimal()) {
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE, EdmSimpleType.Decimal.toString());
                    }
                    if (child.isDouble()) {
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE, EdmSimpleType.Double.toString());
                    }
                    if (child.isBoolean()) {
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE, EdmSimpleType.Boolean.toString());
                    }
                    if (child.isTextual()) {
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE, EdmSimpleType.String.toString());
                    }
                }

                property.appendChild(parent.getOwnerDocument().createTextNode(child.asText()));
            } else if (child.isContainerNode()) {
                if (!typeSet && child.hasNonNull(ODataConstants.JSON_TYPE)) {
                    property.setAttributeNS(
                            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                            ODataConstants.ATTR_M_TYPE, child.get(ODataConstants.JSON_TYPE).textValue());
                }

                final String type = property.getAttribute(ODataConstants.ATTR_M_TYPE);
                if (StringUtils.isNotBlank(type) && EdmSimpleType.isGeospatial(type)) {
                    if (EdmSimpleType.Geography.toString().equals(type)
                            || EdmSimpleType.Geometry.toString().equals(type)) {

                        final String geoType = child.get(ODataConstants.ATTR_TYPE).textValue();
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE,
                                geoType.startsWith("Geo") ? EdmSimpleType.namespace() + "." + geoType
                                        : type + geoType);
                    }

                    if (child.has(ODataConstants.JSON_COORDINATES)
                            || child.has(ODataConstants.JSON_GEOMETRIES)) {
                        GeospatialJSONHandler.deserialize(child, property,
                                property.getAttribute(ODataConstants.ATTR_M_TYPE));
                    }
                } else {
                    buildSubtree(client, property, child);
                }
            }
        }
    }
}

From source file:Main.java

/**
 * * Convenience method to transfer a node (and all of its children) from one
 * * DOM XML document to another./*from   www.  jav  a2  s.c o m*/
 * *
 * * Note: this method is recursive.
 * *
 * * @param current the current Element to append the transfer to
 * * @param target the target document for the transfer
 * * @param n the Node to transfer
 * * @return Element the current element.
 */
public static Element transferNode(Element current, Document target, Node n) {
    String name = n.getNodeName();
    String value = n.getNodeValue();
    short type = n.getNodeType();

    if (type == Node.ELEMENT_NODE) {
        // create a new element for this node in the target document
        Element e = target.createElement(name);

        // move all the attributes over to the target document
        NamedNodeMap attrs = n.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
            Node a = attrs.item(i);
            e.setAttribute(a.getNodeName(), a.getNodeValue());
        }

        // get the children for this node
        NodeList children = n.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            // transfer each of the children to the new document
            transferNode(e, target, children.item(i));
        }

        // append the node to the target document element
        current.appendChild(e);
    } else if (type == Node.TEXT_NODE) {
        Text text = target.createTextNode(value);
        current.appendChild(text);
    }

    return current;
}

From source file:DomUtils.java

/**
 * Add literal text to the supplied element.
 * @param element Target DOM Element.//w  ww  . j  av  a2s  . c om
 * @param literalText Literal text to be added.
 */
public static void addLiteral(Element element, String literalText) {

    Document document = element.getOwnerDocument();
    Text literal = document.createTextNode(literalText);
    element.appendChild(literal);
}

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 source file:com.msopentech.odatajclient.engine.data.ODataBinder.java

/**
 * Gets an <tt>EntryResource</tt> from the given OData entity.
 *
 * @param <T> entry resource type.
 * @param entity OData entity./*from   w  w w .  j a  va  2s . co m*/
 * @param reference reference class.
 * @param setType whether to explicitly output type information.
 * @return <tt>EntryResource</tt> object.
 */
@SuppressWarnings("unchecked")
public static <T extends EntryResource> T getEntry(final ODataEntity entity, final Class<T> reference,
        final boolean setType) {

    final T entry = ResourceFactory.newEntry(reference);
    entry.setType(entity.getName());

    // -------------------------------------------------------------
    // Add edit and self link
    // -------------------------------------------------------------
    final URI editLink = entity.getEditLink();
    if (editLink != null) {
        final LinkResource entryEditLink = ResourceFactory.newLinkForEntry(reference);
        entryEditLink.setTitle(entity.getName());
        entryEditLink.setHref(editLink.toASCIIString());
        entryEditLink.setRel(ODataConstants.EDIT_LINK_REL);
        entry.setEditLink(entryEditLink);
    }

    if (entity.isReadOnly()) {
        final LinkResource entrySelfLink = ResourceFactory.newLinkForEntry(reference);
        entrySelfLink.setTitle(entity.getName());
        entrySelfLink.setHref(entity.getLink().toASCIIString());
        entrySelfLink.setRel(ODataConstants.SELF_LINK_REL);
        entry.setSelfLink(entrySelfLink);
    }
    // -------------------------------------------------------------

    // -------------------------------------------------------------
    // Append navigation links (handling inline entry / feed as well)
    // -------------------------------------------------------------
    // handle navigation links
    for (ODataLink link : entity.getNavigationLinks()) {
        // append link 
        LOG.debug("Append navigation link\n{}", link);
        entry.addNavigationLink(getLinkResource(link, ResourceFactory.linkClassForEntry(reference)));
    }
    // -------------------------------------------------------------

    // -------------------------------------------------------------
    // Append edit-media links
    // -------------------------------------------------------------
    for (ODataLink link : entity.getEditMediaLinks()) {
        LOG.debug("Append edit-media link\n{}", link);
        entry.addMediaEditLink(getLinkResource(link, ResourceFactory.linkClassForEntry(reference)));
    }
    // -------------------------------------------------------------

    // -------------------------------------------------------------
    // Append association links
    // -------------------------------------------------------------
    for (ODataLink link : entity.getAssociationLinks()) {
        LOG.debug("Append association link\n{}", link);
        entry.addAssociationLink(getLinkResource(link, ResourceFactory.linkClassForEntry(reference)));
    }
    // -------------------------------------------------------------

    final Element content = newEntryContent();
    if (entity.isMediaEntity()) {
        entry.setMediaEntryProperties(content);
        entry.setMediaContentSource(entity.getMediaContentSource());
        entry.setMediaContentType(entity.getMediaContentType());
    } else {
        entry.setContent(content);
    }

    for (ODataProperty prop : entity.getProperties()) {
        content.appendChild(toDOMElement(prop, content.getOwnerDocument(), setType));
    }

    return entry;
}

From source file:eu.europa.esig.dss.DSSXMLUtils.java

/**
 * This method creates and adds a new XML {@code Element}
 *
 * @param document  root document//from   w w  w .j a  v a2  s. c o  m
 * @param parentDom parent node
 * @param namespace namespace
 * @param name      element name
 * @return added element
 */
public static Element addElement(final Document document, final Element parentDom, final String namespace,
        final String name) {

    final Element dom = document.createElementNS(namespace, name);
    parentDom.appendChild(dom);
    return dom;
}