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:Main.java

private static Element constructDocument() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Element rootElement = doc.createElement("root");
    doc.appendChild(rootElement);//from  w w  w.  j a va  2  s  . com
    Element c1Element = doc.createElement("c1");
    Element c2Element = doc.createElement("c2");
    Element c3Element = doc.createElement("c3");
    Element gc1Element = doc.createElement("gc1_1");
    Element gc2Element = doc.createElement("gc1_2");
    Text textNode = doc.createTextNode("uncle_freddie");
    Element gc3Element = doc.createElement("gc2_1");

    rootElement.appendChild(c1Element);
    rootElement.appendChild(c2Element);
    rootElement.appendChild(c3Element);

    c1Element.appendChild(gc1Element);
    c1Element.appendChild(gc2Element);
    c2Element.appendChild(gc3Element);

    gc3Element.appendChild(textNode);

    return rootElement;
}

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

public static MISSessionId sendSessionIdRequest(String webServiceURL, byte[] idl, byte[] cert,
        String oaFriendlyName, String redirectURL, String referenceValue, List<String> mandateIdentifier,
        String targetType, byte[] authBlock, SSLSocketFactory sSLSocketFactory)
        throws MISSimpleClientException {
    if (webServiceURL == null) {
        throw new MISSimpleClientException("service.04");
    }/*from   ww w  .j  a v a 2s.com*/
    if (idl == null) {
        throw new NullPointerException("Argument idl must not be null.");
    }
    if (redirectURL == null) {
        throw new NullPointerException("Argument redirectURL must not be null.");
    }

    // ssl settings
    if (sSLSocketFactory != null) {
        SZRGWSecureSocketFactory fac = new SZRGWSecureSocketFactory(sSLSocketFactory);
        Protocol.registerProtocol("https", new Protocol("https", fac, 443));
    }

    try {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element mirElement = doc.createElementNS(MIS_NS, "MandateIssueRequest");
        Element idlElement = doc.createElementNS(MIS_NS, "IdentityLink");

        idlElement.appendChild(doc.createTextNode(new String(Base64.encodeBase64(idl))));
        mirElement.appendChild(idlElement);

        if (cert != null && cert.length > 0) {
            Element certElement = doc.createElementNS(MIS_NS, "X509SignatureCertificate");
            certElement.appendChild(doc.createTextNode(new String(Base64.encodeBase64(cert))));
            //certElement.appendChild(doc.createTextNode(Base64.encodeBase64(cert)));
            //          certElement.appendChild(doc.createTextNode(new String(Base64.encodeBase64(cert))));
            mirElement.appendChild(certElement);
        }

        if (!StringUtils.isEmpty(oaFriendlyName)) {
            Element oaFriendlyNameElement = doc.createElementNS(MIS_NS, "OAFriendlyName");
            oaFriendlyNameElement.appendChild(doc.createTextNode(oaFriendlyName));
            mirElement.appendChild(oaFriendlyNameElement);
        }

        Element redirectElement = doc.createElementNS(MIS_NS, "RedirectURL");
        redirectElement.appendChild(doc.createTextNode(redirectURL));
        mirElement.appendChild(redirectElement);

        Element referenceValueElement = doc.createElementNS(MIS_NS, "ReferenceValue");
        referenceValueElement.appendChild(doc.createTextNode(referenceValue));
        mirElement.appendChild(referenceValueElement);

        if (mandateIdentifier != null && mandateIdentifier.size() > 0) {
            Element filtersElement = doc.createElementNS(MIS_NS, "Filters");
            Element mandateIdentifiersElement = doc.createElementNS(MIS_NS, "MandateIdentifiers");
            for (int i = 0; i < mandateIdentifier.size(); i++) {
                Element mandateIdentifierElement = doc.createElementNS(MIS_NS, "MandateIdentifier");
                mandateIdentifierElement.appendChild(doc.createTextNode(mandateIdentifier.get(i)));
                mandateIdentifiersElement.appendChild(mandateIdentifierElement);
            }
            filtersElement.appendChild(mandateIdentifiersElement);
            mirElement.appendChild(filtersElement);
        }

        //add Target element
        Element targetElement = doc.createElementNS(MIS_NS, "Target");
        Element targetTypeElement = doc.createElementNS(MIS_NS, "Type");
        targetTypeElement.appendChild(doc.createTextNode(targetType));
        targetElement.appendChild(targetTypeElement);
        mirElement.appendChild(targetElement);

        //add AuthBlock element
        Element authBlockElement = doc.createElementNS(MIS_NS, "authBlock");
        authBlockElement.appendChild(doc.createTextNode(new String(Base64.encodeBase64(authBlock))));
        mirElement.appendChild(authBlockElement);

        // send soap request
        Element mandateIssueResponseElement = sendSOAPRequest(webServiceURL, mirElement);

        // check for error
        checkForError(mandateIssueResponseElement);

        // check for session id
        //String sessionId = ((Node) XPathAPI.selectSingleNode(mandateIssueResponseElement, "/mis:MandateIssueResponse/mis:SessionID/text()", NS_NODE)).getNodeValue();
        Node sessionIdNode = ((Node) XPathAPI.selectSingleNode(mandateIssueResponseElement,
                "//mis:MandateIssueResponse/mis:SessionID/text()", NS_NODE));
        if (sessionIdNode == null) {
            throw new MISSimpleClientException("SessionId not found in response.");
        }
        String sessionId = sessionIdNode.getNodeValue();

        Node guiRedirectURLNode = ((Node) XPathAPI.selectSingleNode(mandateIssueResponseElement,
                "//mis:MandateIssueResponse/mis:GuiRedirectURL/text()", NS_NODE));
        if (guiRedirectURLNode == null) {
            throw new MISSimpleClientException("GuiRedirectURL not found in response.");
        }
        String guiRedirectURL = guiRedirectURLNode.getNodeValue();

        // create return object
        MISSessionId msid = new MISSessionId();
        msid.setSessiondId(sessionId);
        msid.setRedirectURL(guiRedirectURL);

        return msid;
    } catch (ParserConfigurationException e) {
        throw new MISSimpleClientException("service.06", e);
    } catch (DOMException e) {
        throw new MISSimpleClientException("service.06", e);
    } catch (TransformerException e) {
        throw new MISSimpleClientException("service.06", e);
    }

}

From source file:Main.java

public static void mergeElement(Element from, Element to) {
    // attrs//from  w  w w .jav  a2  s  .  com
    for (int idx = 0; idx < from.getAttributes().getLength(); idx++) {
        Node node = from.getAttributes().item(idx);
        to.getAttributes().setNamedItem(node.cloneNode(false));
    }

    // children
    for (int idx = 0; idx < from.getChildNodes().getLength(); idx++) {
        Node node = from.getChildNodes().item(idx);

        if (!Element.class.isInstance(node)) {
            continue;
        }

        to.appendChild(node.cloneNode(true));
    }
}

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

private static Element packIntoSOAP(Element element) throws MISSimpleClientException {
    try {//w  w  w .ja va 2  s. co  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:com.msopentech.odatajclient.engine.data.json.GeospatialJSONHandler.java

private static Element deserializeLineString(final Document document, final Iterator<JsonNode> itor) {
    final Element lineString = document.createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_LINESTRING);
    if (!itor.hasNext()) {
        lineString.appendChild(document.createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_POSLIST));
    }//from  www  .  j  a v a2s .c o  m

    appendPoses(lineString, document, itor);

    return lineString;
}

From source file:com.aurel.track.exchange.docx.exporter.CustomXML.java

/**
 * Creates a dom elemebnt and adds to the parent
 * @param parentElement//from  ww w.j a  v a  2s.  co m
 * @param elementName
 * @param elementValue
 * @param dom
 */
private static void appendChild(Element parentElement, String elementName, String elementValue, Document dom) {
    if (parentElement != null && elementValue != null) {
        Element domElement = createDomElement(elementName, elementValue, dom);
        if (domElement != null) {
            parentElement.appendChild(domElement);
        }
    }
}

From source file:Main.java

private static Node replaceTagName(Document document, Node node, String... tags) {

    NodeList nodeList = node.getChildNodes();

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node subNode = nodeList.item(i);
        if (subNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }/*  w  w  w.  ja  v  a  2  s  .  c  o  m*/

        String nodeName = subNode.getNodeName();
        for (int j = 0; j < tags.length / 2; j++) {
            if (nodeName.equals(tags[j])) {
                Element element = document.createElement(tags[j + 1]);
                for (int k = 0; k < subNode.getChildNodes().getLength(); k++) {
                    element.appendChild(subNode.getChildNodes().item(k));
                }

                node.replaceChild(element, subNode);
                subNode = element;
            }
        }

        replaceTagName(document, subNode, tags);
    }

    return node;
}

From source file:com.sitewhere.configuration.ConfigurationMigrationSupport.java

/**
 * Moves event processing elements from previous locations into new element.
 * /*  w w w.  ja v a 2  s  .  c o m*/
 * @param config
 * @param dcomm
 * @param eproc
 * @param document
 * @throws SiteWhereException
 */
protected static void moveEventProcessingElements(Element config, Element dcomm, Element eproc,
        Document document) throws SiteWhereException {
    Element iproc = DomUtils.getChildElementByTagName(dcomm, "inbound-processing-strategy");
    if (iproc != null) {
        dcomm.removeChild(iproc);
        eproc.appendChild(iproc);
    }
    Element ichain = DomUtils.getChildElementByTagName(config, "inbound-processing-chain");
    if (ichain != null) {
        config.removeChild(ichain);
        eproc.appendChild(ichain);
    }
    Element oproc = DomUtils.getChildElementByTagName(dcomm, "outbound-processing-strategy");
    if (oproc != null) {
        dcomm.removeChild(oproc);
        eproc.appendChild(oproc);
    }
    Element ochain = DomUtils.getChildElementByTagName(config, "outbound-processing-chain");
    if (ochain != null) {
        config.removeChild(ochain);
        eproc.appendChild(ochain);
    }
    Element reg = DomUtils.getChildElementByTagName(dcomm, "registration");
    if (reg != null) {
        String qname = (reg.getPrefix() != null) ? (reg.getPrefix() + ":" + "device-services")
                : "device-services";
        document.renameNode(reg, reg.getNamespaceURI(), qname);
    }
}

From source file:Main.java

/**
 * Changes the tag name of an element./*  w ww.  j av a  2  s .  c om*/
 * 
 * @param elem Element which name should be changed
 * @param newName new tag name of the element
 * @return true if the name was changed successfully or false otherwise
 */
static public boolean changeTagName(Element elem, String newName) {
    if (elem == null)
        return false; // not Found!
    Document doc = elem.getOwnerDocument();
    Element newElem = doc.createElement(newName);

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

    // Copy all Child Elements
    for (Node node = elem.getFirstChild(); node != null; node = node.getNextSibling())
        newElem.appendChild(node.cloneNode(true));
    // insert
    Node parent = elem.getParentNode();
    parent.replaceChild(newElem, elem);
    return true;
}

From source file:com.google.visualization.datasource.render.HtmlRenderer.java

/**
 * Generates an HTML string representation of a data table.
 * //  w w w.j  av a2  s .  c  o m
 * @param dataTable The data table to render.
 * @param locale The locale. If null, uses the default from
 *     {@code LocaleUtil#getDefaultLocale}.
 *
 * @return The char sequence with the html string.
 */
public static CharSequence renderDataTable(DataTable dataTable, ULocale locale) {
    // Create an xml document with head and an empty body.
    Document document = createDocument();
    Element bodyElement = appendHeadAndBody(document);

    // Populate the xml document.
    Element tableElement = document.createElement("table");
    bodyElement.appendChild(tableElement);
    tableElement.setAttribute("border", "1");
    tableElement.setAttribute("cellpadding", "2");
    tableElement.setAttribute("cellspacing", "0");

    // Labels tr element.
    List<ColumnDescription> columnDescriptions = dataTable.getColumnDescriptions();
    Element trElement = document.createElement("tr");
    trElement.setAttribute("style", "font-weight: bold; background-color: #aaa;");
    for (ColumnDescription columnDescription : columnDescriptions) {
        Element tdElement = document.createElement("td");
        tdElement.setTextContent(columnDescription.getLabel());
        trElement.appendChild(tdElement);
    }
    tableElement.appendChild(trElement);

    Map<ValueType, ValueFormatter> formatters = ValueFormatter.createDefaultFormatters(locale);
    // Table tr elements.
    int rowCount = 0;
    for (TableRow row : dataTable.getRows()) {
        rowCount++;
        trElement = document.createElement("tr");
        String backgroundColor = (rowCount % 2 != 0) ? "#f0f0f0" : "#ffffff";
        trElement.setAttribute("style", "background-color: " + backgroundColor);

        List<TableCell> cells = row.getCells();
        for (int c = 0; c < cells.size(); c++) {
            ValueType valueType = columnDescriptions.get(c).getType();
            TableCell cell = cells.get(c);
            String cellFormattedText = cell.getFormattedValue();
            if (cellFormattedText == null) {
                cellFormattedText = formatters.get(cell.getType()).format(cell.getValue());
            }

            Element tdElement = document.createElement("td");
            if (cell.isNull()) {
                tdElement.setTextContent("\u00a0");
            } else {
                switch (valueType) {
                case NUMBER:
                    tdElement.setAttribute("align", "right");
                    tdElement.setTextContent(cellFormattedText);
                    break;
                case BOOLEAN:
                    BooleanValue booleanValue = (BooleanValue) cell.getValue();
                    tdElement.setAttribute("align", "center");
                    if (booleanValue.getValue()) {
                        tdElement.setTextContent("\u2714"); // Check mark.
                    } else {
                        tdElement.setTextContent("\u2717"); // X mark.
                    }
                    break;
                default:
                    if (StringUtils.isEmpty(cellFormattedText)) {
                        tdElement.setTextContent("\u00a0"); // nbsp.
                    } else {
                        tdElement.setTextContent(cellFormattedText);
                    }
                }
            }
            trElement.appendChild(tdElement);
        }
        tableElement.appendChild(trElement);
    }
    bodyElement.appendChild(tableElement);

    // Warnings:
    for (Warning warning : dataTable.getWarnings()) {
        bodyElement.appendChild(document.createElement("br"));
        bodyElement.appendChild(document.createElement("br"));
        Element messageElement = document.createElement("div");
        messageElement.setTextContent(
                warning.getReasonType().getMessageForReasonType() + ". " + warning.getMessage());
        bodyElement.appendChild(messageElement);
    }

    return transformDocumentToHtmlString(document);
}