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.europeana.uim.sugarcrmclient.internal.helpers.ClientUtils.java

/**
 * Creates a SelectFields Soap Object given a List<String> fieldnames object
 * which sets the fields to be retrieved.
 * //w w w .j a va  2 s .co m
 * @param fieldnames
 * @return
 */
public static SelectFields generatePopulatedSelectFields(List<String> fieldnames) {

    SelectFields selfields = new SelectFields();
    StringBuffer arrayType = new StringBuffer();
    arrayType.append("string[");
    arrayType.append(fieldnames.size());
    arrayType.append("]");
    CommonAttributes commonAttributes = new CommonAttributes();
    commonAttributes.setHref(arrayType.toString());
    selfields.setCommonAttributes(commonAttributes);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();

        for (String fieldname : fieldnames) {
            Element element = document.createElement("string");
            Array array = new Array();
            array.getAnyList();
            selfields.setArray(array);
            element.appendChild(document.createTextNode(fieldname));
        }

    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return null;
    }

    return selfields;

}

From source file:Main.java

public static void exportXmlFile(ArrayList<?> listObject, String rootElement, String interfaceName,
        String pathSaveFile) {/*from  w w w. j  a v a 2 s .  c  om*/
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
        // creating a new instance of a DOM to build a DOM tree.
        Document doc = docBuilder.newDocument();

        Element root = doc.createElement(rootElement);
        // adding a node after the last child node of the specified node.
        doc.appendChild(root);

        Element interfaceElement = null;

        Element child = null;
        Text text;

        for (Object obj : listObject) {
            Class srcClass = obj.getClass();
            Field[] field = srcClass.getFields();
            interfaceElement = doc.createElement(interfaceName);
            for (int i = 0; i < field.length; i++) {
                // System.out.println(field[i].getName() + ":" +
                // field[i].get(obj));
                child = doc.createElement(field[i].getName());

                text = doc.createTextNode((field[i].get(obj)).toString());
                child.appendChild(text);

                interfaceElement.appendChild(child);
            }
            root.appendChild(interfaceElement);
        }

        // TransformerFactory instance is used to create Transformer
        // objects.
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = sw.toString();

        File file = new File(pathSaveFile);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
        bw.write(xmlString);
        bw.flush();
        bw.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.bluexml.side.Integration.alfresco.xforms.webscript.XmlBuilder.java

@SuppressWarnings("unchecked")
private static Element buildAttributes(Document doc, Map<QName, Serializable> properties) {
    Element attributesE = doc.createElement(ENTRY_ATTRIBUTES_NODE);
    for (Entry<QName, Serializable> entry : properties.entrySet()) {
        Serializable value = entry.getValue();
        if (value != null) {
            Element att = null;/*from  w w  w.j  ava 2s . c  o  m*/
            if (value instanceof Collection) {
                att = buildAttributeCollection(doc, entry.getKey().getLocalName(), (Collection<?>) value);
            } else {
                att = buildAttribute(doc, entry.getKey().getLocalName(), value.toString());
            }
            attributesE.appendChild(att);
        }
    }
    return attributesE;
}

From source file:sep.gaia.resources.poi.POILoaderWorker.java

/**
 * Generates a Overpass API-request in XML-format. The request complies to the limitations and the
 * bounding box in <code>query</code> and is designed to retrieve both nodes and recursed ways.
 * @param query The query to generate XML for.
 * @return The generated XML-query./* w ww  . j  a  v  a 2s .com*/
 */
private static String generateQueryXML(POIQuery query) {
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document doc = docBuilder.newDocument();

        // The root of a OSM-query is always osm-script:
        Element script = doc.createElement("osm-script");
        doc.appendChild(script);

        // First element is the union containing the queries:
        Element unionElement = doc.createElement("union");
        script.appendChild(unionElement);

        // Second element says that the recused union of the prior results should be formed:
        Element recurseUnion = doc.createElement("union");
        Element itemElement = doc.createElement("item");
        recurseUnion.appendChild(itemElement);
        Element recurseElement = doc.createElement("recurse");
        recurseElement.setAttribute("type", "down");
        recurseUnion.appendChild(recurseElement);

        script.appendChild(recurseUnion);

        // The last element means, that the results (of the recursed union)
        // should be written as response:
        Element printElement = doc.createElement("print");
        script.appendChild(printElement);

        // First query (in the query union) askes for nodes conforming the given attributes:
        Element queryNodeElement = doc.createElement("query");
        queryNodeElement.setAttribute("type", "node");

        // The second element does the same for ways:
        Element queryWayElement = doc.createElement("query");
        queryWayElement.setAttribute("type", "way");

        // Add them to the first union:
        unionElement.appendChild(queryNodeElement);
        unionElement.appendChild(queryWayElement);

        // Now iterate all key-value-pairs and add "has-kv"-pairs to both queries:
        POIFilter filter = query.getLimitations();
        Map<String, String> attributes = filter.getLimitations();

        for (String key : attributes.keySet()) {
            String value = attributes.get(key);

            // The values returned by POIFilter are regular expressions, so use regv instead of v:
            Element currentKVNode = doc.createElement("has-kv");
            currentKVNode.setAttribute("k", key);
            currentKVNode.setAttribute("regv", value);
            queryNodeElement.appendChild(currentKVNode);

            Element currentKVWay = doc.createElement("has-kv");
            currentKVWay.setAttribute("k", key);
            currentKVWay.setAttribute("regv", value);
            queryWayElement.appendChild(currentKVWay);

        }

        // We don't want the data of the whole earth, so add bounding-boxes to the queries:
        Element nodeBBoxElement = createBBoxElement(doc, query.getBoundingBox());
        queryNodeElement.appendChild(nodeBBoxElement);

        Element wayBBoxElement = createBBoxElement(doc, query.getBoundingBox());
        queryWayElement.appendChild(wayBBoxElement);

        // Now the XML-tree is built, so transform it to a string and return it:
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(stream);

        transformer.transform(source, result);

        return stream.toString();

    } catch (ParserConfigurationException | TransformerException e) {
        Logger.getInstance().error("Cannot write cache-index: " + e.getMessage());
        return null;
    }
}

From source file:com.microsoft.tfs.util.xml.DOMUtils.java

/**
 * Adds a new {@link Element} node to a {@link Document} tree as a child of
 * the specified parent {@link Element}.
 *
 * @param parent//from  w ww  .j  a  v a2 s  .  c  o  m
 *        the parent {@link Element} (must not be <code>null</code>)
 * @param namespaceURI
 *        the namespace URI to put the new child in, or <code>null</code>
 * @param qualifiedName
 *        the qualified name to give the new child (must not be
 *        <code>null</code>)
 * @return the new child {@link Element} (never <code>null</code>)
 */
public static Element appendChildNS(final Element parent, final String namespaceURI,
        final String qualifiedName) {
    Check.notNull(parent, "parent"); //$NON-NLS-1$

    final Element newChild = parent.getOwnerDocument().createElementNS(namespaceURI, qualifiedName);
    parent.appendChild(newChild);
    return newChild;
}

From source file:Main.java

/**
 * Add a CDATA element with attributes.//from  w  ww .j a v a 2s.co  m
 * <p/>
 * NOTE: Serializing a XML document via TRAX changes "\r\n" to "\r\r\n" in
 * a CDATA section. Serializing with the Xalan XMLSerializer works fine.
 *
 * @param parent parent node
 * @param name   node name
 * @param data   node data
 * @param attrs  attributes
 */
public static Element addCDATAElement(Node parent, String name, String data, Attr[] attrs) {
    Element element;
    CDATASection cdata;
    if (parent instanceof Document) {
        element = ((Document) parent).createElement(name);
        /*
         * Creates a <code>CDATASection</code> node whose value is the
         * specified.
         */
        cdata = ((Document) parent).createCDATASection(data);
    } else {
        element = parent.getOwnerDocument().createElement(name);
        cdata = parent.getOwnerDocument().createCDATASection(data);
    }

    if (attrs != null && attrs.length > 0) {
        for (Attr attr : attrs) {
            element.setAttributeNode(attr);
        }
    }

    element.appendChild(cdata);
    parent.appendChild(element);
    return element;
}

From source file:com.osafe.services.SiteMapServices.java

private static void createFriendlyMapNode(String URL, ProductContentWrapper productContentWrapper,
        CategoryContentWrapper categoryContentWrapper, CategoryContentWrapper parentCategoryContentWrapper,
        String featureDescription, String contentSeoFriendlyName) {

    StringBuilder urlBuilder = new StringBuilder();
    String productName = null;/*www .j  a v  a2 s  .c o  m*/
    String parentCategoryName = null;
    String categoryName = null;
    String friendlyKey = null;
    String friendlyValue = null;
    StringBuilder friendlyKeyValue = new StringBuilder();

    try {
        List<String> pathElements = StringUtil.split(URL, "/");
        String sUrlTarget = pathElements.get(pathElements.size() - 1);

        friendlyKey = StringUtil.replaceString(sUrlTarget, "&", "~");
        friendlyKey = StringUtil.replaceString(friendlyKey, "=", "^^");

        if (productContentWrapper != null) {
            productName = productContentWrapper.get("PRODUCT_NAME").toString();
        }

        if (parentCategoryContentWrapper != null) {
            parentCategoryName = parentCategoryContentWrapper.get("CATEGORY_NAME").toString();
        }

        if (categoryContentWrapper != null) {
            categoryName = categoryContentWrapper.get("CATEGORY_NAME").toString();
        }

        if (UtilValidate.isNotEmpty(parentCategoryName)) {
            friendlyKeyValue.append(parentCategoryName + "/");
        }

        if (UtilValidate.isNotEmpty(categoryName)) {
            friendlyKeyValue.append(categoryName);
        }

        if (UtilValidate.isNotEmpty(productName)) {
            if (UtilValidate.isNotEmpty(featureDescription)) {
                productName = productName + " " + featureDescription;
            }
            friendlyKeyValue.append("/" + productName);
        }
        if (UtilValidate.isNotEmpty(contentSeoFriendlyName)) {
            friendlyKeyValue.append(contentSeoFriendlyName);
        }
        friendlyValue = friendlyKeyValue.toString();
        friendlyValue = StringUtil.replaceString(friendlyValue, "&apos;", "");
        friendlyValue = StringUtil.replaceString(friendlyValue, "'", "");
        friendlyValue = StringUtil.replaceString(friendlyValue, "&quot;", "");
        friendlyValue = StringUtil.replaceString(friendlyValue, "\"", "");
        friendlyValue = StringUtil.replaceString(friendlyValue, "&amp;", "And");
        friendlyValue = StringUtil.replaceString(friendlyValue, "&", "And");
        friendlyValue = StringUtil.replaceString(friendlyValue, ",", "");
        //Do not replace '-' if this was a static page friendly name (contentAttribute type=SEO_FRIENDLY_URL) 
        if (UtilValidate.isEmpty(contentSeoFriendlyName)) {
            friendlyValue = StringUtil.replaceString(friendlyValue, "-", "");
        }
        friendlyValue = StringUtil.replaceString(friendlyValue, ".", "");
        friendlyValue = StringUtil.replaceString(friendlyValue, " ", "-");

        Element newElement = document.createElement("property");
        newElement.setAttribute("key", friendlyKey);
        Element newChildElement = document.createElement("value");
        newChildElement.setAttribute("xml:lang", "en");
        newChildElement.appendChild(document.createTextNode(friendlyValue.toLowerCase()));
        newElement.appendChild(newChildElement);
        rootElement.appendChild(newElement);

    } catch (Exception e) {
        Debug.logError(e, module);

    }
}

From source file:de.betterform.xml.xforms.model.constraints.RelevanceSelector.java

private static void addElement(Element relevantParent, Node instanceNode) {
    Document relevantDocument = relevantParent.getOwnerDocument();
    Element relevantElement;/*  ww  w .j  ava  2s  .  c o m*/

    if (instanceNode.getNamespaceURI() == null) {
        relevantElement = relevantDocument.createElement(instanceNode.getNodeName());
    } else {
        relevantElement = relevantDocument.createElementNS(instanceNode.getNamespaceURI(),
                instanceNode.getNodeName());
    }

    // needed in instance serializer ...
    relevantElement.setUserData("", instanceNode.getUserData(""), null);

    relevantParent.appendChild(relevantElement);
    addAttributes(relevantElement, instanceNode);
    addChildren(relevantElement, instanceNode);
}

From source file:it.intecs.pisa.toolbox.util.URLReader.java

public static void getContent(String url, Document urlTree, Element fatherNode) throws Exception {
    Element directoryNode = urlTree.createElement("directory");
    directoryNode.setAttribute("name", url);
    fatherNode.appendChild(directoryNode);
    try {/*from  w w w .  j  ava  2s .c o m*/
        String[] filesToDw = URLReader.getFileToDW("/" + SCHEMA + url);
        int index = 0;
        while (index < filesToDw.length) {
            Element fileNode = urlTree.createElement("file");
            fileNode.setAttribute("name", filesToDw[index]);
            directoryNode.appendChild(fileNode);
            index++;
        }

        String[] directoryToDw = URLReader.getDirectoryToDW("/" + SCHEMA + url);
        index = 0;
        while (index < directoryToDw.length) {
            getContent(directoryToDw[index], urlTree, directoryNode);
            index++;
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

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

private static Element deserializePolygon(final Document document, final Iterator<JsonNode> itor) {
    final Element polygon = document.createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_POLYGON);

    if (itor.hasNext()) {
        final Iterator<JsonNode> extItor = itor.next().elements();
        final Element exterior = document.createElementNS(ODataConstants.NS_GML,
                ODataConstants.ELEM_POLYGON_EXTERIOR);
        polygon.appendChild(exterior);
        final Element extLR = document.createElementNS(ODataConstants.NS_GML,
                ODataConstants.ELEM_POLYGON_LINEARRING);
        exterior.appendChild(extLR);//from ww w  . j  a va 2 s  . c  o  m

        appendPoses(extLR, document, extItor);
    }

    if (itor.hasNext()) {
        final Iterator<JsonNode> intItor = itor.next().elements();
        final Element interior = document.createElementNS(ODataConstants.NS_GML,
                ODataConstants.ELEM_POLYGON_INTERIOR);
        polygon.appendChild(interior);
        final Element intLR = document.createElementNS(ODataConstants.NS_GML,
                ODataConstants.ELEM_POLYGON_LINEARRING);
        interior.appendChild(intLR);

        appendPoses(intLR, document, intItor);
    }

    return polygon;
}